简体   繁体   English

MySQL select 具有不同值的所有行同一列

[英]MySQL select all rows with different values same column

I have the following tables:我有以下表格:

Table configs:表配置:

id config
1 ip
2 os
3 cpu

Table options表选项

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

The config_id column in table options is a foreign key to the id field in table configs表选项中的 config_id 列是表配置中 id 字段的外键

I have a third table users_configs that links users with configs and options like so:我有第三个表 users_configs 将用户与配置和选项链接起来,如下所示:

Table users_configs表 users_configs

id user_id config_id, option_id
1 123      1          1
2 456      2          2
3 789      3          3

I would like to get all users that have the following both options at the same time:我希望同时拥有以下两个选项的所有用户:

- os: windows
- cpu: AMD

I tried the following query, but because of the OR, this returns all users that have either os:windows OR 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)

Any help will be appreciated thanks.任何帮助将不胜感激。

You can use joins so you can compare one row of user_configs to another row of user_configs, such that they have the same user_id and then join each of these rows to the respective lookup tables for the os and cpu values.您可以使用连接,以便将一行 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'

You can use aggregation:您可以使用聚合:

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;

The where gets users that have either option. where 让用户可以选择其中一种。 The HAVING guarantees that a user has both. HAVING保证用户同时拥有两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM