加入选择SQL查询?

时间:2013-02-16 16:47:09

标签: sql join

我正在尝试在一个表(Wordpress使用的一个)上运行查询,我想从一个表中选择ID和post_type列,然后在两个单独的时间执行左连接到另一个表(获取单独的数据) )。

这是我到目前为止所做的,但它并没有削减芥末:

SELECT derby_posts.id        AS pID, 
       derby_posts.post_type AS tier 
FROM   derby_posts 
       LEFT JOIN (SELECT derby_postmeta.post_id  AS dbID1, 
                         derby_postmeta.meta_key AS dbMeta1) 
              ON pid = dbid1 
                 AND dbmeta1 = 'twitter' 
       LEFT JOIN (SELECT derby_postmeta.post_id  AS dbID2, 
                         derby_postmeta.meta_key AS dbMeta2) 
              ON pid = dbid2 
                 AND dbmeta2 = 'website' 
WHERE  tier IN ('local', 'regional', 'national')

我确定我错过了一些非常简单的东西......

编辑:这是适合我的解决方案。表别名有帮助,​​将所有SELECT语句放在一起清理了一些东西。此外,我意识到我可以从SELECT中删除项目,即使我在Join中使用它们,这会清理结果。

SELECT 
    db.ID as id, 
    db.post_type as tier,
    dpm1.meta_value as twitter,
    dpm2.meta_value as website
FROM derby_posts db
LEFT JOIN derby_postmeta dpm1 ON (db.ID = dpm1.post_id AND dpm1.meta_key = 'twitter' )
LEFT JOIN derby_postmeta dpm2 ON (db.ID = dpm2.post_id AND dpm2.meta_key = 'website' )
WHERE db.post_type IN ('local','regional','national')

2 个答案:

答案 0 :(得分:2)

  

我确定我错过了一些超级简单的东西......

你是对的!

您需要为select提供别名,并在ON子句中使用该别名。您还缺少FROM <table> - 从表中读取的SELECT语句的必需部分:

LEFT JOIN (
    SELECT derby_postmeta.post_id  AS dbID1, 
           derby_postmeta.meta_key AS dbMeta1
    FROM someTable
) dpm ON pid = dpm.dbid1 AND dpm.dbmeta1 = 'twitter'

我提供了SELECT别名dpm的结果,并将其用于“链接”内部选择的行与外部选择的行。

答案 1 :(得分:1)

SELECT 
    db.derby_posts.ID as pID, 
    db.derby_posts.post_type as tier,
    dpm1.post_id as dbID1,
    dpm1.meta_key as dbMeta1,
    dpm2.post_id as dbID2,
    dpm2.meta_key as dbMeta2
FROM derby_posts db
LEFT JOIN derby_postmeta dpm1 ON (db.pID = dpm1.post_id AND dpm1.meta_key= 'twitter')
LEFT JOIN derby_postmeta dpm2 ON (db.pID = dbm2.post_id AND dbm2.meta_key = 'website')
WHERE tier IN ('local','regional','national')