Mysql 如何进行此查询

Mysql 如何进行此查询,mysql,Mysql,有一个花店的数据表,看起来像 CustomerID Flower John peony John lily John Lotus Mary peony Mary lily Mary chrysanthemum Lisa

有一个花店的数据表,看起来像

 CustomerID        Flower

    John                peony
    John                lily
    John                Lotus

    Mary               peony
    Mary               lily
    Mary               chrysanthemum

    Lisa                chrysanthemum
    Lisa                peony
    Lisa                kapok

enter code here
我想找到那些购买相同n花的客户ID。例如,在上表中,对于牡丹花和百合花,同时购买这两种花的客户n=2,在本例中为John和Mary

我无法找到执行上述查询的SQL语句。请帮忙。
谢谢

从[yourtable]中选择客户ID,其中Flower='牡丹'或'百合'

你希望它是动态的吗


然后可能会用变量创建一个存储过程。有关sp的更多信息

请从[yourtable]中选择客户ID、Flower,其中Flower='Painy'或'lily'

你希望它是动态的吗

然后可能会用变量创建一个存储过程。有关sp的更多信息

自我加入如何

SELECT 
    y.CustomerID 
FROM 
    YourTable y 
JOIN 
    YourTable y2 
ON 
    y.CustomerID = y2.CustomerId 
WHERE
    y.Flower = "Lily"
AND
    y2.Flower = "Lotus"
自我加入怎么样

SELECT 
    y.CustomerID 
FROM 
    YourTable y 
JOIN 
    YourTable y2 
ON 
    y.CustomerID = y2.CustomerId 
WHERE
    y.Flower = "Lily"
AND
    y2.Flower = "Lotus"

将表本身连接起来

SELECT a.CustomerID, b.CustomerID, a.Flower FROM flowertable a, flowertable b WHERE a.Flower = b.Flower

将表本身连接起来

SELECT a.CustomerID, b.CustomerID, a.Flower FROM flowertable a, flowertable b WHERE a.Flower = b.Flower

你需要这样的东西

select distinct(CustomerID) from mytable 
where flower in
(select distinct(flower) from mytable group  by  flower having count(flower) = 2)

您可以将2替换为您想要的任何数字

你需要这样的东西

select distinct(CustomerID) from mytable 
where flower in
(select distinct(flower) from mytable group  by  flower having count(flower) = 2)

您可以将2替换为您想要的任何数字

我会尝试使用exists条款,该条款只会报告具有多个不同购买者的鲜花:

select a.customerid, a.flower
from yourtable a
where exists
  (select 'x'
   from yourtable b 
   where b.customerid <> a.customerid
   and b.flower = a.flower)

我将尝试使用exists条款,该条款仅报告具有多个不同购买者的鲜花:

select a.customerid, a.flower
from yourtable a
where exists
  (select 'x'
   from yourtable b 
   where b.customerid <> a.customerid
   and b.flower = a.flower)
这将回报约翰|玛丽|莉莉,他想回报约翰|莉莉和牡丹这将回报约翰|玛丽|莉莉,他想回报约翰|莉莉和牡丹