如何解决MySQL选择同一列具有不同值的所有行
我有以下表格:
表格配置:
id config
1 ip
2 os
3 cpu
表格选项
id config_id option
1 1 127.0.0.1
2 1 192.168.0.1
3 2 windows
4 2 linux
5 3 AMD
6 3 Intel
table options 中的 config_id 列是 table configs 中 id 字段的外键
我有第三个表 users_configs 将用户与配置和选项联系起来,如下所示:
表 users_configs
id user_id config_id,option_id
1 123 1 1
2 456 2 2
3 789 3 3
我希望所有用户同时拥有以下两个选项:
- os: windows
- cpu: AMD
我尝试了以下查询,但由于 OR,这将返回具有 os:windows 或 cpu: AMD 的所有用户。
SELECT * FROM users_configs
LEFT JOIN options ON options.id = users_configs.option_id
WHERE (options.config_id = 2 OR options.config_id = 3)
感谢任何帮助。
解决方法
您可以使用连接,以便将一行 user_configs 与另一行 user_configs 进行比较,使它们具有相同的 user_id,然后将这些行中的每一行连接到各自的 os 和 cpu 值查找表。
SELECT u1.user_id
FROM users_configs AS u1
JOIN users_configs AS u2 ON u1.user_id=u2.user_id
JOIN config AS c1 ON u1.config_id=c1.id
JOIN config AS c2 ON u2.config_id=c2.id
JOIN options AS o1 ON u1.option_id=o1.id
JOIN options AS o2 ON u2.option_id=o2.id
WHERE c1.config='os' AND o1.option='windows'
AND c2.config='cpu' AND o2.option='AMD'
,
您可以使用聚合:
SELECT uc.user_id
FROM users_configs uc JOIN
options o
ON o.id = uc.option_id join
config c
ON c.id = uc.config_id
WHERE (c.config = 'os' AND o.option 'windows') OR
(c.config = 'cpu' AND o.option = 'AMD')
GROUP BY uc.user_id
HAVING COUNT(DISTINCT c.config) = 2;
获取具有任一选项的用户的位置。 HAVING
保证用户同时拥有两者。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。