SQL one-to-many relationship - How to SELECT rows depending on multiple to-many properties? [duplicate]

淺唱寂寞╮ 提交于 2021-01-05 09:26:10

问题


A MySQL database contains two tables with a one-to-many relationship: One user can have many settings:

Users:
id    username    password
--------------------------
 1    Bob         123
 2    Alice       abc
 ...


Settings:
id   user_id   key     value
-----------------------------
 1   1         color   blue   // Bobs settings...
 2   1         theme   xy
 3   1         size    5
 4   2         size    5      // Alices settings...

Problem: How to find all users with color == blue AND size == 5?

Using a LEFT JOIN it is no problem to find users with one property:

SELECT users.id FROM users LEFT JOIN settings ON users.id = settings.user_id WHERE settings.key = 'color' AND settings.value = 'blue'

However, this does not work when searching for two settings at a time?

Is it possible to solve this with a single statement? What is the most efficient way to query this data?


回答1:


One method uses aggregation and having:

select s.user_id
from settings s
where (key, value) in (  ('color', 'blue'), ('size', '5') )
group by s.user_id
having count(*) = 2;

This assumes that there are no duplicate settings (if so, you would need to use count(distinct)).



来源:https://stackoverflow.com/questions/51153040/sql-one-to-many-relationship-how-to-select-rows-depending-on-multiple-to-many

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