Mysql

GROUP BY 重寫具有易於互換的 AND OR 條件的子查詢

  • September 2, 2015

表:

content        tag_map       extrainfo
|id|title|    |id|tagid|    |id|lat|lng|
|--|-----|    |--|-----|    |--|---|---|
|1 |Lorem|    |1 |8    |    |3 |0,4|0,1|
|2 |Ipsum|    |2 |9    |    |2 |1,1|1,2|
|3 |Dolor|    |1 |9    |
             |1 |7    |   

id 是唯一索引

SELECT * FROM content, tag_map, extrainfo
WHERE
tag_map.id = content.id
AND
extrainfo.id = content.id

#AND OR conditions here
#conditions can be very different but I would like
#to use the same query structure
#just change conditions here as necessary

GROUP BY content.id

此查詢有效 - 但速度很慢。我發現大多數替代方案都涉及子查詢,但是我想不出一種使用子查詢的方法,並且仍然能夠自由更改涉及所有表中的列的****AND OR條件。

也歡迎其他非子查詢方法。

首先清理連接語法:

SELECT * FROM content as c
inner join tag_map as t on c.id=t.id 
inner join extrainfo as e on c.id=e.id
WHERE
#AND OR conditions here
#conditions can be very different but I would like
#to use the same query structure
#just change conditions here as necessary
GROUP BY c.id

現在用你的 and/or 子句代替上面的 rem’d 行。然後研究索引這些列(索引應該涵蓋條件中的所有欄位)。

這些簡單的步驟將大大加快速度。如果您需要進一步加速,請在加速結果之前和之後發布現有索引的完整詳細資訊。

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