SQL排除内连接表

时间:2013-01-30 13:56:57

标签: sql inner-join

我有一个表格,其中包含两个我关注的列

Business_ID   /   Product type

我正在尝试编写一个SQL查询,以便只获得销售一种类型但不会销售其他类型的商家。因此该表填充了

B_ID    prod_type
123  |   A
123  |   A
123  |   B
234  |   A
234  |   C
234  |   C
456  |   A
456  |   D
789  |   A

然后列表继续。我正在尝试编写一个SQL语句,它将找到一个销售prod_type A而不是prod_type B,C,D的B_ID。这是我正在尝试但它不起作用

SELECT phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*) 
FROM phop phop_1, phop phop_2
WHERE phop_1.Business_id = phop_2.Business_id
  AND phop_1.PRODUCT_TYPE = 'A'
  AND NOT phop_2.PRODUCT_TYPE = 'B'
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE

我还发现了如何排除使用外连接,但由于它是同一个表我不能这样做,除非有办法在进行连接之前选择prod_type A.

select phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*) 
from phop phop_1
LEFT OUTER JOIN phop phop_2
ON phop_1.Business_id = phop_2.Business_id
WHERE phop_2.Business_id IS NULL
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE

3 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

SELECT DISTINCT p.BusinessId
FROM phop p
   LEFT JOIN phop p2 ON p.BusinessId = p2.BusinessId AND p2.Product_Type <> 'A'
WHERE p2.BusinessId IS NULL

Fiddle

祝你好运。

答案 1 :(得分:1)

首先选择只有一种产品类型的商家,然后将其加入原始表格。

DECLARE @tbl TABLE
    (
     B_ID INT,
     prod_type VARCHAR(100)
    )

INSERT  INTO @tbl
        (B_ID, prod_type)
VALUES  (123, 'A'),
        (123, 'A'),
        (123, 'B'),
        (234, 'A'),
        (234, 'C'),
        (234, 'C'),
        (456, 'A'),
        (456, 'D'),
        (789, 'A') ;

WITH    businessIdsWithOneProductType
          AS (SELECT    B_ID
              FROM      @tbl t
              GROUP BY  B_ID
              HAVING    COUNT(DISTINCT prod_type) = 1)
    SELECT  *
    FROM    businessIdsWithOneProductType
            INNER JOIN @tbl ON businessIdsWithOneProductType.B_ID = [@tbl].B_ID

答案 2 :(得分:0)

SELECT a.*
FROM    tableName a
        LEFT JOIN tableName b
            ON a.B_ID = b.B_ID AND
                b.prod_type IN ('B','C','D')
WHERE b.B_ID IS NULL