如果我有一张桌子
CREATE TABLE users (
id int(10) unsigned NOT NULL auto_increment,
name varchar(255) NOT NULL,
profession varchar(255) NOT NULL,
employer varchar(255) NOT NULL,
PRIMARY KEY (id)
)
我想获得所有专业领域的独特价值,什么会更快(或建议):
SELECT DISTINCT u.profession FROM users u
or
SELECT u.profession FROM users u GROUP BY u.profession
?
如果问题允许,请尝试使用EXISTS,因为它被优化为只要找到结果就结束(并且不缓冲任何响应),因此,如果您只是试图为这样的WHERE子句规范化数据
SELECT FROM SOMETHING S WHERE S.ID IN ( SELECT DISTINCT DCR.SOMETHING_ID FROM DIFF_CARDINALITY_RELATIONSHIP DCR ) -- to keep same cardinality
更快的回答是:
SELECT FROM SOMETHING S WHERE EXISTS ( SELECT 1 FROM DIFF_CARDINALITY_RELATIONSHIP DCR WHERE DCR.SOMETHING_ID = S.ID )
这并不总是可行的,但当可用时,你会看到一个更快的响应。