I’ve been relying on CREATE VIEW and aliasing a lot to create SQL queries, and am sure there’s probably a much more efficient way to go about it. Can anyone offer any general advice? Here’s my latest abomination:
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
After doing some research into different types of joins and better ways to use aliasing, my SQL code is much more condensed and efficient (doesn’t take as long to run). The answer was two-fold: use the proper JOIN method to reduce the number of rows returned – INNER JOIN was particularly helpful in most cases (see http://www.w3schools.com/sql/sql_join_inner.asp) – and use aliasing to join the same table on multiple columns.
The latter solution was particularly helpful, because what I was doing before was essentially creating four or five views (using CREATE VIEW) in order to return data and then filter that data based on other criteria. For example, I was using a “CREATE VIEW view1 AS SELECT” statement to return rows a, b, c, and d, and then using a “SELECT a FROM view1 WHERE criterion” statement to filter the data. Sometimes this was repeated multiple times.
A more efficient way to accomplish the same task was to use multiple JOINs on the same table using aliasing. Combined with INNER JOIN for most queries, it substantially reduced query time and returned the same rows as the more complex statements.
Example:
This method has been a life saver.