sql - SQL查询多个多值
问题描述
我在尝试查询表时遇到了一些问题。我正在尝试查询所有具有多种颜色的用户 ID。所以我希望结果只有 222,因为它有红色和蓝色值。
我努力了:
SELECT userid FROM test_table WHERE color = 'red' AND color = 'blue';
SELECT userid FROM test_table WHERE color LIKE '%red%' AND color LIKE '%blue%';
我尝试对这两个查询使用 or ,但它们返回所有内容。
| userid | color |
+--------+-------+
| 222 | red |
| 222 | red |
| 333 | red |
| 333 | red |
| 222 | blue |
| 444 | blue |
解决方案
我认为您可以使用聚合和having
:
select userid
from t
where color in ('red', 'blue')
group by userid
having count(distinct color) = 2;
推荐阅读
- python - Pandas - 读取文本文件
- node.js - 访问嵌套的 React App 路由时出现 NGINX 404 错误
- react-native - React Navigation v.5 选项卡栏图标导航到模态
- ios - 使用 FCM 仅向开发安装发送推送通知
- css - 在导航栏的中心对齐元素,除了一个(或多个)元素
- php - Laravel 发送电子邮件没有数据
- google-chrome - 在没有 SameSite=None 的情况下禁用 chrome 阻止 cookie
- node.js - 如何从查找表中仅选择几个值
- java - 如何修复 UnsatisfiedLinkError?
- angular - 将 sessionStorage 中的数据保存为角度未定义