选择没有特定值的项目

时间:2011-02-01 15:59:29

标签: mysql

我有产品表 - 每个产品表都有几个类别;每个类别都有一个主列。 (我还有一个类别表和一个product_categories表。)

如果main = 1 - >这是主要类别

我想选择所有主要类别的产品(与此产品相关的所有类别都没有main = 1列。)

这是选择所有主要类别的方法:

SELECT *
  FROM categories
 WHERE id IN (SELECT DISTINCT category_id
                FROM `product_categories`
               WHERE main = 1);

如何找到没有主要类别的产品?

4 个答案:

答案 0 :(得分:2)

正如您所提到的我想选择所有不具有主要类别的产品(与此产品相关的所有类别都没有main = 1列)。

这就是你所追求的

select * from products where prod_id not in (select distinct prod_id from categories where main =1);

我有点尝试过。

mysql> desc products;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| prod_id | int(11)      | YES  |     | NULL    |       |
| name    | varchar(100) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> desc categories;
+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| prod_id | int(11) | YES  |     | NULL    |       |
| cat_id  | int(11) | YES  |     | NULL    |       |
| main    | int(11) | YES  |     | NULL    |       |
+---------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from products;
+---------+-------+
| prod_id | name  |
+---------+-------+
|       1 | prod1 |
|       2 | prod2 |
|       3 | prod3 |
|       4 | prod4 |
+---------+-------+
4 rows in set (0.00 sec)

mysql> select * from categories;
+---------+--------+------+
| prod_id | cat_id | main |
+---------+--------+------+
|       1 |      1 |    1 |
|       1 |      2 |    2 |
|       2 |      1 |    2 |
|       2 |      1 |    3 |
|       3 |      2 |    1 |
|       3 |      4 |    2 |
+---------+--------+------+
6 rows in set (0.00 sec)

mysql> select * from products where prod_id not in (select distinct prod_id from categories where main =1);
+---------+-------+
| prod_id | name  |
+---------+-------+
|       2 | prod2 |
|       4 | prod4 |
+---------+-------+
2 rows in set (0.00 sec)

答案 1 :(得分:1)

SELECT * FROM products WHERE id NOT IN(SELECT product_id FROM product_categories WHERE main = 1)

答案 2 :(得分:1)

从性能的角度来看,我发现过去并没有证明麻烦。如果上述建议很慢,您可能会尝试...

SELECT *
    FROM PRODUCTS
    WHERE NOT EXISTS (SELECT *
                          FROM PRODUCT_CATEGORIES
                          WHERE MAIN = 1 AND
                                PRODUCT_CATEGORIES.PRODUCT_ID = PRODUCTS.ID)

虽然作为Knuth's dictum的粉丝,我建议你先用最简单的方式编码,如果出现问题,只会担心它。

答案 3 :(得分:0)

如果“product_categories”中包含“product_id”字段,并且字段“id”包含“products”表。

查询看起来像;

select p.*
from products p
left join product_categories pc on pc.product_id = p.id and pc.main = 1
where pc.category_id is null
group by p.id