2012-08-04 44 views
0

两个表的SQL查询我有两个表:具有参考键

Discounts(disid primary key) 

Cust(custid primary key, disid ref discount(disid)) 

现在我需要一个查询来获取custid让所有disid(优惠券),并且客户可以包含相同disid不止一次。

+2

一个简单的加入不会做呢?如果没有更多的信息需要 – 2012-08-04 14:48:49

回答

1
select custid, count(distinct disid) from cust 
group by custid 
having count(*) = (select count(*) from discounts) 
1
SELECT COUNT(DISTINCT D.disid) FROM CUST C 
INNER JOIN DISCOUNTS D ON D.disid=C.disid GROUP BY D.disid 
1

尝试这两种解决方案:

SELECT a.custid, COUNT(a.disid) totalCoupon 
FROM cust a 
      INNER JOIN discounts b 
       ON b.disid = a.disid 
GROUP BY a.custid 

SELECT a.custid, COUNT(a.disid) totalCoupon 
FROM cust a 
      INNER JOIN discounts b 
       ON b.disid = a.disid 
GROUP BY a.custid 
HAVING COUNT(a.disid) > 1 -- customers having the same (but more than 1) 
          -- CouponID will only be shown here