mySQL innoDB 中哪个查询更快且冗余更少?
Which query is more fast and less redundant in mySQL innoDB?
SELECT * FROM inv, clients
WHERE inv.client_id = clients.ID
AND ( inv.type = "STA"
OR inv.type = "FIN" )
或
SELECT * FROM invoice, clients
WHERE inv.client_id = clients.ID
AND MATCH (inv.type) AGAINST ("STA FIN")
我知道这是 2 个问题,但也许它们会放在一起[=13=]
简答:使用 inv.type IN ("STA", "FIN")
和 INDEX(client_id, type)
。
长答案:
MATCH...AGAINST
非常慢,除非你在 type
上有一个 FULLTEXT
索引。但是,这是对FULLTEXT
的误用,所以不推荐
AND ( inv.type = "STA" OR inv.type = "FIN" )
自动变成 AND inv.type IN ("STA", "FIN")
,相当快。如果有 INDEX(type)
,它可能会使用该索引并且非常快。它的效用取决于基数——"type" 听起来像是一个具有很少不同值的列,因此索引可能没有用。
另一个问题:不要使用过时的 "commajoin",请使用 JOIN...ON
:
SELECT *
FROM invoice
JOIN clients ON inv.client_id = clients.ID -- How the tables relate
WHERE inv.type IN ("STA", "FIN") -- filtering
你应该
inv: INDEX(client_id, type)
使用 'composite' 索引可以处理 ON 和 WHERE,同时避免我上面提到的 "low cardinality" 问题。
SELECT * FROM inv, clients
WHERE inv.client_id = clients.ID
AND ( inv.type = "STA"
OR inv.type = "FIN" )
或
SELECT * FROM invoice, clients
WHERE inv.client_id = clients.ID
AND MATCH (inv.type) AGAINST ("STA FIN")
我知道这是 2 个问题,但也许它们会放在一起[=13=]
简答:使用 inv.type IN ("STA", "FIN")
和 INDEX(client_id, type)
。
长答案:
MATCH...AGAINST
非常慢,除非你在 type
上有一个 FULLTEXT
索引。但是,这是对FULLTEXT
的误用,所以不推荐
AND ( inv.type = "STA" OR inv.type = "FIN" )
自动变成 AND inv.type IN ("STA", "FIN")
,相当快。如果有 INDEX(type)
,它可能会使用该索引并且非常快。它的效用取决于基数——"type" 听起来像是一个具有很少不同值的列,因此索引可能没有用。
另一个问题:不要使用过时的 "commajoin",请使用 JOIN...ON
:
SELECT *
FROM invoice
JOIN clients ON inv.client_id = clients.ID -- How the tables relate
WHERE inv.type IN ("STA", "FIN") -- filtering
你应该
inv: INDEX(client_id, type)
使用 'composite' 索引可以处理 ON 和 WHERE,同时避免我上面提到的 "low cardinality" 问题。