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