仅当表B中的条目等于表C中的条目时,才将表B加入表A.

时间:2018-03-07 14:32:25

标签: mysql sql database

我有3张桌子。客户,销售和潜在销售 基本结构如下:

客户表:
+-----------+-------+----------------+ | client_id | name | address | +-----------+-------+----------------+ | 1 | john | 12 blue ave | | 2 | paul | 34 green lane | | 3 | peter | 69 yellow road | +-----------+-------+----------------+

潜在销售表:
+----------+------------+---------------------+ |product_id | client_id | received_free_promo | +-----------+------------+---------------------+ | 3 | 1 | 1 | | 4 | 2 | 0 | | 5 | 2 | 1 | +-----------+------------+---------------------+

销售:
+----------+-----------+-----------+ | sales_id | client_id | product_id | +----------+-----------+------------+ | 1 | 2 | 4 | | 2 | 43 | 4 | | 3 | 2 | 5 | | 4 | 18 | 93 | +----------+-----------+------------+

我想加入客户和potential_sales表仅限
1)received_promo等于1和
2)他们实际购买了促销包(即潜在销售的product_id有进入销售表的条目)。如果他们最终没有购买free_promo产品,那么我根本不想加入客户端和potential_sales表。这很重要 - 我不能简单地JOIN来解决这个问题,因为这只是更大查询的一小部分,我无法无缘无故地加入。

(以下是我希望它如何工作。它主要是伪代码来描述我想要发生的事情) SELECT c.* FROM clients c LEFT JOIN potential_sales ps ON ps.client_id=c.id LEFT JOIN sales ps ON s.product_id=ps.product_id IF(s.sales_id) JOIN potential_sales ps ON ps.client_id=c.id

我如何在MySQL中执行此操作?我还没有接近解决方案。请帮忙!

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT A.*, B.product_id, B.received_free_promo
FROM Clients A JOIN 
    (SELECT * FROM PotentialSales 
     WHERE received_free_promo=1) B
ON A.client_id=B.client_id
WHERE EXISTS (SELECT 1 FROM Sales C
                 WHERE A.client_id=C.client_id 
                      AND B.product_id=C.product_id);

请参阅Demo on SQL Fiddle.

答案 1 :(得分:0)

您缺少的是EXISTS子句:

SELECT
    C.*,
    P.*
FROM
    Clients AS C
    INNER JOIN PotentialSales AS P ON C.client_id = P.client_id
WHERE
    P.received_free_promo = 1 AND
    EXISTS (
        SELECT
            'the client already sold that product'
        FROM
            Sales AS S
        WHERE
            S.client_id = C.client_id AND
            S.product_id = P.product_id)

答案 2 :(得分:0)

试试这个......“从客户端选择*作为c自然加入潜力,作为p加入销售,作为s在p.product_id = s.product_id,其中received_promo = 1”。 select *将提到所有3个表中的所有内容。你可以选择你想要的结果。