我有一张像
这样的表格表1:
word id
a 1
a 2
a 10
c 1
d 2
e 30
f 10
现在,如果word = 'a'
,那么我需要找出'c'
和''d'和'f'。
我写了一个查询,它的工作但是花了太多时间,因为表包含了大量的数据。
查询:
SELECT DISTINCT word
FROM table1
WHERE id IN (SELECT id
FROM table1
WHERE word = 'a')
答案 0 :(得分:1)
SELECT DISTINCT(t1.word)
FROM table1 t1
INNER JOIN table1 t2 ON (t1.id = t2.id AND t2.word = 'a')
这应该更快,因为它没有做子查询。
此外,添加索引(即单词)将有助于加快查询速度。
答案 1 :(得分:1)
您可以使用自我加入:
SELECT DISTINCT t1.word
FROM table1 t1
JOIN table1 t2 on t1.id = t2.id
WHERE t2.word = 'a'
但当然你需要适当的索引。
答案 2 :(得分:0)
试试这个......
SELECT t.word
FROM table1 t
INNER JOIN Table1 tt ON t.id = tt.id AND t.word <> 'a'
WHERE tt.word = 'a'
另一种方式是......
SELECT t.word
FROM table1 t
INNER JOIN Table1 tt ON t.id = tt.id
WHERE tt.word = 'a' AND t.word <> 'a'
答案 3 :(得分:0)
通常EXISTS
优于IN
关于效果。所以,请尝试这个:
SELECT DISTINCT word
FROM table1 t1
WHERE EXISTS(SELECT *
FROM table1 t2
WHERE t2.word = 'a' and t2.id = t1.a)
但请注意,有很多时候需要采用其他技术来提高查询的性能。正如其他人所提到的,创建索引是一种选择。
答案 4 :(得分:0)
尝试:
SELECT DISTINCT t1.word FROM table1 AS t1
INNER JOIN table1 AS t2 ON t1.id = t2.id
WHERE t2.word = 'a'