1

我正在尝试对一个表(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')
4

2 回答 2

2

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

你说的对!

您需要给您select的 s 一个别名,并在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'

我给了你的结果SELECTan alias dpm,并用它来“链接”从内部选择的行到你的外部选择的行。

于 2013-02-16T16:50:28.703 回答
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')
于 2013-02-16T16:52:29.430 回答