我这里的桌子结构很简单。只是与一个简单的user_id相关的单词列表。
Word Table:
word - varchar(50)
user_id - integer我需要找到一个用户使用的词,而其他用户没有使用。目前,我正在执行此操作,它在Postgresql (9.0.3)上的工作时间为200 k字(~3.5-5秒),并且在MySQL上完全崩溃(5.1.54),它具有相同的数据(5+ mins并且仍在运行)。所有已使用的列都被编入索引。
SELECT
word, count(word) as count
FROM
words
WHERE
word not in (select word from words where user_id <> 99 group by word)
and user_id = 99
GROUP BY word
ORDER BY count desc LIMIT 20( 1)有人知道更好的方法吗?
2)有人知道为什么在MySql上它完全失败了?
编辑:这解决了MySQL上的问题,从5 mins+到10-20 to谢谢Borealid。
SELECT
word, count(word) as count
FROM
words
WHERE
word not in (select distinct word from words where user_id <> 99)
and user_id = 99
GROUP BY word
ORDER BY count desc LIMIT 20谢谢。
发布于 2011-02-22 14:27:09
尝试不存在():
SELECT
w1.word,
COUNT(w1.word) as count
FROM
words w1
WHERE
NOT EXISTS (
SELECT 1
FROM
words w2
WHERE
w2.user_id <> 99
AND
w1.word = w2.word
)
AND
w1.user_id = 99
GROUP BY
w1.word
ORDER BY
count DESC
LIMIT 20;确保您在user_id和word (或组合)上有一个索引,使用explain查看查询计划,以及什么对您最合适。
======编辑:还可以使用IS尝试左联接解决方案:
SELECT
w1.word,
COUNT(w1.word) AS count
FROM
words w1
LEFT JOIN words w2 ON (w1.word = w2.word AND w1.user_id <> w2.user_id)
WHERE
w1.user_id = 99
AND
w2.word IS NULL
GROUP BY
w1.word
ORDER BY
count DESC
LIMIT 20;在这两列上尝试索引:
CREATE INDEX idx_word_user ON words ( word, user_id);https://stackoverflow.com/questions/5079145
复制相似问题