我一直依靠CREATE VIEW和別名來創建SQL查詢,並且肯定可能有更高效的方法去實現它。任何人都可以提供一般建議嗎?這是我最新的憎惡:如何減少基於CREATE VIEW的長SQL查詢?
SELECT associations2.object_id, associations2.term_id, associations2.cat_ID, associations2.term_taxonomy_id
FROM (SELECT objects_tags.object_id, objects_tags.term_id, wp_cb_tags2cats.cat_ID, categories.term_taxonomy_id
FROM (SELECT wp_term_relationships.object_id, wp_term_taxonomy.term_id, wp_term_taxonomy.term_taxonomy_id
FROM wp_term_relationships
LEFT JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
ORDER BY object_id ASC, term_id ASC)
AS objects_tags
LEFT JOIN wp_cb_tags2cats ON objects_tags.term_id = wp_cb_tags2cats.tag_ID
LEFT JOIN (SELECT wp_term_relationships.object_id, wp_term_taxonomy.term_id as cat_ID, wp_term_taxonomy.term_taxonomy_id
FROM wp_term_relationships
LEFT JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE wp_term_taxonomy.taxonomy = 'category'
GROUP BY object_id, cat_ID, term_taxonomy_id
ORDER BY object_id, cat_ID, term_taxonomy_id)
AS categories on wp_cb_tags2cats.cat_ID = categories.term_id
WHERE objects_tags.term_id = wp_cb_tags2cats.tag_ID
GROUP BY object_id, term_id, cat_ID, term_taxonomy_id
ORDER BY object_id ASC, term_id ASC, cat_ID ASC)
AS associations2
LEFT JOIN categories ON associations2.object_id = categories.object_id
WHERE associations2.cat_ID <> categories.cat_ID
GROUP BY object_id, term_id, cat_ID, term_taxonomy_id
ORDER BY object_id, term_id, cat_ID, term_taxonomy_id
首先,子選項內的「order by」子句不起作用 - 唯一的「order by」重要的是最後一個。此外,我想知道是否可以擺脫「group by」子句 - 我不確定你想用這些子句實現什麼,因爲你似乎沒有使用任何聚合函數。你有一個子選擇,你有別名「類別」,但你似乎也有一個名爲「類別」的表。我知道這不是你問的,但是這使得事情變得非常混亂。 (...繼續...) – 2012-02-20 07:31:25
最後,你似乎有多個連接到wp_term_relationships和wp_term_taxonomy。你可能不需要這樣做,但是我很難說,因爲我不知道這個查詢試圖達到什麼目的。 – 2012-02-20 07:32:14