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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号