我正在查詢wordpress posts帖子中的一些帖子,並通過多次加入postmeta表獲取多個元值。我對帖子欄和元值也有很多條件。查詢似乎正在工作,但我很好奇,如果我已經把條件放在正確的地方。比較以下查詢,這些查詢將最有效/最有效地獲得帖子ID及其相關元數據?Mysql多個連接到一個表具有不同的條件 - 他們去哪裏?
這一個:
SELECT a.ID as `post_id`, b.meta_value as `metaval1`, c.meta_value as `metaval2`, d.meta_value as `metaval3`
FROM posts AS a
JOIN postmeta AS b ON (b.post_id = a.ID AND b.meta_key = 'metakey1')
LEFT JOIN postmeta as c ON (c.post_id = a.ID AND c.meta_key = 'metakey2')
LEFT JOIN postmeta as d ON (d.post_id = a.ID AND d.meta_key = 'metakey3')
WHERE
b.meta_value != 10
AND a.post_status = 'pending'
AND a.post_date < '2013-03-07 00:00:00'
AND a.post_type = "post"
ORDER BY a.post_date DESC
LIMIT 100;
或這一個:
SELECT a.ID as `post_id`, b.meta_value as `metaval1`, c.meta_value as `metaval2`, d.meta_value as `metaval3`
FROM posts AS a
JOIN postmeta AS b ON (b.post_id = a.ID)
LEFT JOIN postmeta as c ON (c.post_id = a.ID)
LEFT JOIN postmeta as d ON (d.post_id = a.ID)
WHERE
b.meta_key = 'metakey1'
AND b.meta_value != 10
AND c.meta_key = 'metakey2'
AND d.meta_key = 'metakey3'
AND a.post_status = 'pending'
AND a.post_date < '2013-03-07 00:00:00'
AND a.post_type = "post"
ORDER BY a.post_date DESC
LIMIT 100;
任何意見,將不勝感激:)
可能重複的[SQL JOIN在哪裏放置WHERE條件?](http://stackoverflow.com/questions/15483808/sql-join-where-to-place-the-where-condition)第二個是不正確,請參閱我提供的鏈接中的原因。 – Sebas 2013-03-22 19:00:52
相關,是的,大多是重複的。一般來說,最好將盡可能多的相關條件放入'JOIN'條件中,特別是在處理某種外連接時。相信我,未來的維護者會感謝你。並且可能是你的優化器。 – 2013-03-22 19:58:53
哈哈,男人,我發誓我第一次上下尋找。似乎我在搜索查詢中包含了太多細節。 – technosis 2013-03-22 20:41:58