dqch34769 2015-11-22 19:07
浏览 183
已采纳

SQL JOIN在同一个表上有2个条件

I need to combine 2 columns into 1 row. The key between the columns is the post_id.

Here is my table (postmeta):

post_id     meta_key    meta_value
36          cp_state    California
37          cp_state    Illinois
38          cp_state    California
39          cp_state    California
40          cp_state    California
36          cp_city     Los Angeles
37          cp_city     Chicago
38          cp_city     San Diego
39          cp_city     San Diego
40          cp_city     Los Angeles

And here is what im trying to output:

post_id     state       city
36          California  Los Angeles
37          Illinois    Chicago
38          California  San Diego
39          California  San Diego
40          California  Los Angeles

Here is the SQL i used but get a crazy amount of results:

SELECT a.post_id AS pID, a.meta_value AS state, b.meta_value AS city
FROM $wpdb->prefix"."postmeta AS a
LEFT JOIN $wpdb->prefix"."postmeta AS b
ON b.post_id = a.post_id
WHERE a.meta_key = 'cp_state'
AND b.meta_key = 'cp_city'

In the live Wordpress table im using, there's obviously hundreds of other meta_key, so i need it to filter just for these 2 meta_key (cp_city, cp_state)

  • 写回答

1条回答 默认 最新

  • dongziche8030 2015-11-22 19:14
    关注

    You should use INNER JOIN instead of LEFT JOIN

    SELECT a.post_id AS pID, a.meta_value AS state, b.meta_value AS city
    FROM       $wpdb->prefix"."postmeta AS a
    INNER JOIN $wpdb->prefix"."postmeta AS b
    ON b.post_id = a.post_id
    WHERE a.meta_key = 'cp_state'
    AND b.meta_key = 'cp_city'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办