首页 > 解决方案 > 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  |

标签: sql

解决方案


我认为您可以使用聚合和having

select userid
from t
where color in ('red', 'blue')
group by userid
having count(distinct color) = 2;

推荐阅读