duanchique1196 2016-10-01 18:56
浏览 48
已采纳

使用PHP + MySQL左连接来组合来自2个查询的结果

Here's where I'm getting stuck. I have two tables that I'm trying to pull information from. One table contains data of interest under the idand post_title columns, the other contains data under the post_id, meta_key, and meta_value columns.

I have an array of numbers stored in $in, by which I can filter the data from both tables.

To return the id and post_title from the first table is a simple:

$query = "SELECT id, post_title FROM wplz_posts WHERE id IN ($in)";

This of course returns a name and a unique ID for that name, for example:

[id] => 8 
[post_title] => Rustic Wooden Chair

I however also want to grab a price associated with the id returned above, and a single query to do that would look something like:

$query = "SELECT meta_value 
FROM wplz_postmeta 
WHERE post_id IN ($in) AND meta_key = '_price'";

My issue is that I'd like to be able to return all of this data to a single array with one query instead of two, that way both the post_title and the meta_value will correspond to each single number in $in (say, 8) which will then allow me to return the query to an array and then loop through that array as needed. I honestly have spent quite a bit of time on this and I think what I am trying to do requires a "LEFT JOIN", but after multiple videos and tutorials I haven't been able to figure out how to make this elusive technique work. Thank you for your help. :)

  • 写回答

3条回答 默认 最新

  • dtxf759200 2016-10-01 19:03
    关注

    You would want to do an INNER JOIN that looks like this:

    $query = "SELECT p.id, p.post_title, pm.meta_value
    FROM wplz_posts p
    INNER JOIN wplz_postmeta pm ON pm.post_id=p.id
    WHERE p.id IN ($in)
    AND pm.meta_key = '_price'";
    

    You need to join on the id and post_id keys but also filter the join based on the meta_key value which is _price

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看