Mysql

mySQL INNER JOIN 和條件

  • August 29, 2022

我寫了一個 mySQL 查詢,它可以按我的需要工作。

SELECT COUNT(wp_posts.ID) as count, wp_terms.term_id
FROM wp_terms 
INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id AND wp_term_taxonomy.taxonomy = "post_tag"
INNER JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id 
INNER JOIN wp_posts ON wp_posts.ID = wp_term_relationships.object_id AND wp_posts.post_date >= DATE_SUB(NOW(),INTERVAL 24 HOUR) AND wp_posts.post_status = "publish" 
GROUP BY wp_terms.term_id ORDER BY count DESC;

正如你所看到的,當我加入到彼此的表中時,我有條件。

WHERE但我真的,如果我在最後添加一個語句會有什麼變化?

像這樣:

SELECT COUNT(wp_posts.ID) as count, wp_terms.name
FROM wp_terms 
INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id AND wp_term_taxonomy.taxonomy = "post_tag"
INNER JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id 
INNER JOIN wp_posts ON wp_posts.ID = wp_term_relationships.object_id AND wp_posts.post_date >= DATE_SUB(NOW(),INTERVAL 24 HOUR) AND wp_posts.post_status = "publish"
WHERE wp_posts.post_date >= DATE_SUB(NOW(),INTERVAL 24 HOUR) AND wp_posts.post_status = "publish" AND wp_term_taxonomy.taxonomy = "post_tag" 
GROUP BY wp_terms.term_id ORDER BY count DESC;

他們都給了我相同的結果。

我真的很想知道,有什麼區別?

您的兩個查詢不會給出相同的結果 - 一個獲取term_id,一個獲取name。(我會假設這只是一個錯字……)

第二個查詢不必要地重複了post_date和上的測試post_status。刪除ON因為…

ON告訴兩個表是如何“相關”的。 WHERE過濾結果。因為它們之間INNER JOIN沒有功能上的區別。但它有助於閱讀查詢以將測試放在一個地方或另一個地方。

SELECT語法有嚴格的順序:

SELECT
expression(s) to fetch
FROM
JOIN(s) with ON
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT (and OFFSET)

如果你得到“相同”的結果,那麼也許所有的分類值都是“post_tag”?

WHERE如果這是您要的,則不能有兩個子句。

添加此外掛: WP Index Improvements

或者,這些索引可能有助於提高速度:

wp_terms:  INDEX(term_id,  name)
wp_posts:  INDEX(post_status, post_date, ID)
wp_term_taxonomy:  INDEX(taxonomy, term_id)
wp_term_relationships:  INDEX(term_taxonomy_id,  object_id)

引用自:https://dba.stackexchange.com/questions/316155