简体   繁体   English

Mysql从两个表中选择没有关系

[英]Mysql select no relation from two tables

I have two tables first one has PRODUCTS_ID and second table has the relation between products for example product 1 has relation with product (2,3,4,5) as shown in PRODUCT_CONN .我有两个表,第一个表有PRODUCTS_ID ,第二个表有产品之间的关系,例如产品 1 与产品 (2,3,4,5) 有关系,如PRODUCT_CONN所示。 What I need to get the products listed on Table 1 that has no relation to product 1 then the result should be like that "6,7,8".我需要得到表 1 中列出的与产品 1 无关的产品,那么结果应该是“6,7,8”。

TABLE 1
========
PRODUCTS_ID
    1   
    2   
    3   
    4
    5
    6
    7
    8   

TABLE2
======
PRODUCT_ID  | PRODUCT_CONN
    1       |   2
    1       |   3
    1       |   4
    1       |   5

One way you can do this, is joining both tables, and then filtering the rows for discard those that have relations with product ID 1 , like in next example:您可以这样做的一种方法是连接两个表,然后过滤行以丢弃与产品ID 1有关系的行,如下例所示:

SELECT
    TABLE_1.PRODUCTS_ID
FROM
   TABLE_1
LEFT JOIN
   TABLE_2 ON TABLE_2.PRODUCT_CONN = TABLE_1.PRODUCTS_ID
WHERE
   TABLE_1.PRODUCTS_ID <> 1
AND
   (TABLE_2.PRODUCT_ID IS NULL OR TABLE_2.PRODUCT_ID <> 1)

Alternatively, you could first select all IDs that are connected to product with ID 1 , and then select all IDs that are not in this set, excluding also product ID 1 , like this:或者,您可以首先选择与ID 为 1 的产品相关联的所有 ID,然后选择不在此集合中的所有 ID,也不包括产品ID 1 ,如下所示:

SELECT
    PRODUCTS_ID
FROM
    TABLE_1
WHERE
    PRODUCTS_ID NOT IN (SELECT PRODUCT_CONN
                        FROM TABLE_2
                        WHERE PRODUCT_ID = 1)
AND
    PRODUCTS_ID <> 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM