I have a table like
table1:
word id
a 1
a 2
a 10
c 1
d 2
e 30
f 10
Now if word= 'a'
then I need to find out 'c'
and `'d' and 'f'. I wrote a query, its working but taking too much time, because table include huge data.
Query:
SELECT DISTINCT word
FROM table1
WHERE id IN (SELECT id
FROM table1
WHERE word = 'a')
SELECT DISTINCT(t1.word)
FROM table1 t1
INNER JOIN table1 t2 ON (t1.id = t2.id AND t2.word = 'a')
This should be quicker since it's not doing a subquery.
In addition adding indexes (ie on word) will help speed up the query.
You could use a self join:
SELECT DISTINCT t1.word
FROM table1 t1
JOIN table1 t2 on t1.id = t2.id
WHERE t2.word = 'a'
but you'll need appropriate indexes of course.
Try this...
SELECT t.word
FROM table1 t
INNER JOIN Table1 tt ON t.id = tt.id AND t.word <> 'a'
WHERE tt.word = 'a'
Else another way is ....
SELECT t.word
FROM table1 t
INNER JOIN Table1 tt ON t.id = tt.id
WHERE tt.word = 'a' AND t.word <> 'a'
Usually EXISTS
is preferred over IN
regarding the performance. So, please try this one as well:
SELECT DISTINCT word
FROM table1 t1
WHERE EXISTS(SELECT *
FROM table1 t2
WHERE t2.word = 'a' and t2.id = t1.a)
However, please note, there are many times that it becomes necessary to employ other techniques to improvement the performance of the queries. As others have mentioned, creating indexes is one option.
try:
SELECT DISTINCT t1.word FROM table1 AS t1
INNER JOIN table1 AS t2 ON t1.id = t2.id
WHERE t2.word = 'a'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.