Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'IN' clause in mysql making the execution slower, is there any other choices?

Tags:

sql

php

mysql

i have a table named 'language' as shown below

personid |     lang
-------------------
1       |    english
1       |    french
1       |    italian
2       |    italian
3       |    french
3       |    italian
4       |    japanese

I wish to select all personid's with any of the language that personid 1 know. (That is, any personid which have values english, french or italaian)

I have used the following query and got the solution. But it seems little bit slower. (I think it's due to 'IN' clause). Is there any other query option for faster execution.

SELECT distinct personid FROM language WHERE personid!=1 AND lang IN (SELECT lang FROM language WHERE personid=1)

1 Answers

You can do a self-join of the language table:

SELECT DISTINCT l2.personid AS personid FROM
language l1 INNER JOIN language l2
ON l1.lang = l2.lang
WHERE l1.personid = 1;

Output:

+----------+
| personid |
+----------+
|    2     |
|    3     |
+----------+
like image 192
Tim Biegeleisen Avatar answered Feb 06 '26 08:02

Tim Biegeleisen