说我有一个简单的表
cust location
001 USA
001 India
002 Ranchacucamunga
002 Ala-Lemu
我想找到去过美国和印度的人。
我想的是:
SELECT
CASE location
WHEN location is both USA and India
THEN foo
ELSE bar
END
我不知道如何做WHEN
部分。而且我不知道将GROUP BY
放在哪里!
根据我的经验,MySQL只想返回行。如何让MySQL检查字段中是否存在多个值?
编辑
两种解决方案都同样出色我接受了之前的解决方案。
答案 0 :(得分:2)
通常你会使用INTERSECT,但由于INTERSECT在MySQL中不可用,你必须使用等效的JOIN,或者使用已经建议的计数:
select a.cust from
( select cust from simple_table t1 where t1.location = 'USA') a
inner join
( select cust from simple_table t2 where t2.location = 'India' ) b on a.cust = b.cust
你可以写得更好,如下(我的眼睛更具可读性):
select
cust
from
simple_table t1
inner join
simple_table t2 using (cust)
where
t1.location = 'USA' and t2.location = 'India';
答案 1 :(得分:1)
您可以使用where语句指定您的位置
SELECT *
FROM table
WHERE location IN ('USA', 'India')
如果您希望客户同时执行此操作
SELECT cust, group_concat(location)
FROM table
WHERE location IN ('USA', 'India')
GROUP BY cust
HAVING count(*) > 1
对于至少一次去过美国和印度的客户,您可以这样做
SELECT cust, GROUP_CONCAT(location) as locations, sum(location = 'USA') as num_loc, sum(location = 'India') as num_loc1
FROM table
WHERE location IN ('USA', 'India')
GROUP BY cust
HAVING count(*) > 1 AND num_loc > 0 AND num_loc1 > 0
请注意,您可以将> 0
更改为任意次。如果你想要两次访问美国的客户和印度两次只是改变
HAVING count(*) > 1 AND num_loc > 0 AND num_loc1 > 0
至HAVING count(*) > 1 AND num_loc > 1 AND num_loc1 > 1