Mysql subselect alternative

妖精的绣舞 提交于 2019-12-11 18:56:46

问题


I have a query that I know can be done using a subselect, but due to large table sizes (100k+ rows per table) I would like to find an alternative using a join. This is not a homework question, but it's easier to share an example in such terms.

Suppose there are two tables:
Students
:id :name
1   Tom
2   Sally
3   Ben

Books
:id  :student_id  :book
1    1                  Math 101
2    1                  History
3    2                  NULL
4    3                  Math 101

I want to find all students who don't have a history book. Working subselect is:
select name from students where id not in (select student_id from books where book = 'History');

This returns Sally and Ben.

Thanks for your replies!


回答1:


Is performance the problem? Or is this just some theoretical (homework?) question to avoid a subquery? If it's performance then this:

SELECT *
FROM studnets s
WHERE NOT EXISTS
(SELECT id FROM books WHERE student_id = s.id AND book = 'History')

will perform a lot better than the IN you're doing on MySQL (on some other databases, they will perform equivalently). This can also be rephrased as a join:

SELECT s.*
FROM studnets s
LEFT JOIN books b ON s.id = b.student_id AND b.book = 'History'
WHERE b.id IS NULL


来源:https://stackoverflow.com/questions/923438/mysql-subselect-alternative

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!