获取与条件匹配的连接表中包含2个或更多条目的记录

时间:2015-02-13 17:13:01

标签: mysql sql

客户

id INT PK name VARCHAR

细节

id INT PK detail_name VARCHAR

customers_details

customer_id INT FK detail_id INT FK value INT


对于每个customer,我有一组details。 以下查询将获得详细信息#2等于10的所有用户:

SELECT c.* FROM customers c
INNER JOIN customers_details cd ON cd.customer_id = c.customer_id
WHERE cd.detail_id = 2 AND cd.value = 10

我的问题是我需要获得具有2个或更多特定customers的所有details。例如:我希望获得所有customers的详细信息#2 = 10 AND 详细信息#3 = 20。

使用SQL有一种简单的方法吗?

5 个答案:

答案 0 :(得分:1)

我会这样做:

select c.*
from customers_details cd
inner join customers c
    on c.id = cd.customer_id
where cd.detail_id in (2,10)
group by cd.customer_id
having     
    sum(cd.detail_id = 2 and cd.value = 1) = 1
    and sum(cd.detail_id = 10) = 1

我在这里做的是:

  • 按客户分组详情
  • 如果条件满足则求和1。如果有详细信息= 2
  • 仅过滤具有两种条件的客户
  • 我使用WHERE子句,以便在尝试避免全扫描时再次过滤HAVING过滤器的结果。

此致

答案 1 :(得分:0)

您只是在寻找拥有多个详细ID的客户,其中一个等于2,一个等于20?

SELECT c.customer_id, count (*) FROM customers c
INNER JOIN customers_details cd ON cd.customer_id = c.customer_id
WHERE cd.detail_id IN (2, 20) 
GROUP BY c.customer_id
HAVING count(*) > 1

这应该为每个customer_id提供一个detail_id为2 的detail_id为20

答案 2 :(得分:0)

使用分组依据

SELECT c.customer_id
, min(c.name) customer_name
, count(cd.customer_id) detailcount
FROM customers c
INNER JOIN customers_details cd ON cd.customer_id = c.customer_id
WHERE cd.Value is not null
group by c.customer_id
having COUNT(cd.customer_id)>=2

答案 3 :(得分:0)

select *
from customers as c
where exists (
    select 1
    from customer_details as cd
    where
        cd.customer_id = c.customer_id and
        (detail_id = 2 and value = 10 or detail_id = 3 and value = 20)
    having count(*) = 2
)

小心parens。不确定某些平台是否需要在子查询上使用having子句进行分组。如果有group by cd.customer_id,您可以添加虚拟组。

答案 4 :(得分:0)

您可以使用count (distinct detail_id) = 2选择所有同时包含详细信息ID的客户

select c.* from customers_details cd
join customers c on c.id = cd.customer_id
where (detail_id = 2 and value = 10)
or (detail_id = 3 and value = 20)
group by customer_id
having count (distinct detail_id) = 2
相关问题