-1

如果我有两张桌子,一张是:

| ID |  MAKER |
---------------
|  1 |  Honda |
|  2 | Toyota |
|  3 |   Ford |
|  4 |  Honda |
|  5 |   Ford |
|  6 |  Honda |

其中 id 是汽车 ID 号,而 maker 是汽车的制造商

另一个是

购买

| CUSTID | CARID |
------------------
|      1 |     1 |
|      1 |     4 |
|      1 |     6 |
|      2 |     1 |
|      2 |     2 |
|      2 |     4 |
|      2 |     6 |
|      3 |     2 |
|      4 |     5 |
|      4 |     2 |

其中 custid 是客户的 ID,而 carid 是特定汽车的 ID

有没有办法将两者结合起来,然后找出哪些客户购买了所有的Hondas

4

3 回答 3

1

您需要使用 连接两个表CarID,将其分组CustID并需要使用HAVING子句来获取 CarID 在 1、4、6 中的所有记录。此处3HAVING条款表示 CarID 的数量(即 1,4 和 6)。

SELECT P.CustID, COUNT(CarID)
  FROM Purchase P
  JOIN Car C
    ON P.Carid = C.ID
 WHERE CarID IN (1,4,6)
 GROUP BY CustID
HAVING COUNT(CarID) = 3;

或者直接使用名称代替 ID:

SELECT P.CustID, COUNT(CarID)
  FROM Purchase P
  JOIN Car C
    ON P.Carid = C.ID
 WHERE Maker = 'Honda'
 GROUP BY CustID
HAVING COUNT(CarID) = 3;

要获取计数(例如,在这种情况下为 3),请使用此查询

SELECT COUNT(Maker) FROM Car WHERE Maker = 'Honda';

所以你的整个查询可以是这样的:

SELECT P.CustID, COUNT(CarID)
  FROM Purchase P
  JOIN Car C
    ON P.Carid = C.ID
 WHERE Maker = 'Honda'
 GROUP BY CustID
HAVING COUNT(CarID) = (SELECT COUNT(Maker) FROM Car WHERE Maker = 'Honda');

输出:

╔════════╦══════════════╗
║ CUSTID ║ COUNT(CARID) ║
╠════════╬══════════════╣
║      1 ║            3 ║
║      2 ║            3 ║
╚════════╩══════════════╝
于 2013-07-09T04:49:10.373 回答
0

试试这个查询:

select P.CustID
from purchase P
inner join CAR C on P.CarID=C.CarID
WHERE C.Maker like '%Honda%'
group by CustID
having count(P.CarID)=
    (select count(*) from CAR C where C.Maker like '%Honda%')

SQL 小提琴

于 2013-07-09T04:48:51.393 回答
0

尝试这个 :

SELECT A.*, B.*, C.* FROM purchase AS A
INNER JOIN(customer AS B) ON(A.cust_id = B.cust_id)
INNER JOIN(car AS C) ON(A.car_id = C.car_id)
WHERE A.car_id = '1'

我假设你有customer桌子。请记住,您的purchase表必须有一个主字段,如purchase_id. 这WHERE A.car_id = '1'是一个条款,你的本田 ID 是1

于 2013-07-09T04:54:12.637 回答