你会怎么做这个SQL查询?

时间:2010-10-13 19:48:30

标签: sql mysql

假设我在MySQL表中有3个表,其中包含以下字段。

产品

product_id
product_name

类别

category_id
category_name

product_in_category

product_in_category_id
product_id
category_id

您建议使用哪种查询来获取当前未分配到“product_in_category”表中某个类别的所有产品的列表?

性能非常重要,这些表格非常重要。

7 个答案:

答案 0 :(得分:6)

select a.* from product a
left join product_in_category b on a.product_id = b.product_id
where b.product_id is null

答案 1 :(得分:5)

使用LEFT JOIN / IS NULL:

   SELECT p.*
     FROM PRODUCT p
LEFT JOIN PRODUCT_IN_CATEGORY pic ON pic.product_id = p.product_id
    WHERE pic.product_in_category_id IS NULL

使用NOT IN

SELECT p.*
  FROM PRODUCT p
 WHERE p.product_id NOT IN (SELECT pic.product_id
                              FROM PRODUCT_IN_CATEGORY pic)

使用NOT EXISTS

SELECT p.*
  FROM PRODUCT p
 WHERE NOT EXISTS (SELECT NULL
                     FROM PRODUCT_IN_CATEGORY pic
                    WHERE pic.product_id = p.product_id)

哪个最好?

这取决于被比较的列是否可以为空(值可以为NULL)。如果他们是nullable, then NOT IN/NOT EXISTS are more efficient。如果列为not nullable, then LEFT JOIN/IS NULL is more efficient (MySQL only)

答案 2 :(得分:3)

我会使用左连接。

如果您环顾四周,可以找到包含但不存在的答案。

SELECT
  p.product_id, 
  product_name
FROM
   product p
   left join product_in_category pc
   on p.product_id = pc.product_id
WHERE
 pc.product_id is null

答案 3 :(得分:3)

基本上有三种方法可以做到:

SELECT  p.*
FROM    product p
LEFT JOIN
        product_in_category pc
ON      pc.product_id = pc.product_id
WHERE   pc.product_id IS NULL

SELECT  p.*
FROM    product p
WHERE   product_id NOT IN
        (
        SELECT  product_id
        FROM    product_in_category
        )

SELECT  p.*
FROM    product p
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    product_in_category pc
        WHERE   pc.product_id = p.product_id
        )

只要product_in_category.product_id被编入索引,它们都很好,但LEFT JOINNOT IN的效率会更高。

请参阅此文章以进行性能比较:

答案 4 :(得分:2)

SELECT product_id
from products p
 where not exists (select 1
                   from product_in_category pc
                   where pc.product_id = p.product_id)

答案 5 :(得分:1)

SELECT Product_name from Product
WHERE ProductID not in (SELECT product_id FROM product_in_category)

答案 6 :(得分:0)

独家联接总是表现不佳。这是一个可能有助于mysql独占连接的链接:

http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

HTH