[英]How to select rows, which have all or none corresponding values in another table?
I'm not sure I phrased the question correctly, so feel free to correct me. 我不确定我是否正确地表达了这个问题,所以请随时纠正我。 Here are the tables with their data:
以下是包含其数据的表格:
product category category_product
------- -------- ----------------
id_product id_category active id_category id_product
1 1 1 1 1
2 2 1 2 1
3 3 0 1 2
4 0 2 2
3 2
3 3
4 3
I need to select only those products, which have all categories as inactive. 我只需要选择那些将所有类别都设为非活动状态的产品。 For example:
例如:
1
is good, since it belongs to active categories ( 1
, 2
). 1
是好的,因为它属于活性类别( 1
, 2
)。 2
is good, since it has at least one active category ( 1
, 2
; 3
- inactive) 2
是良好的,因为它具有至少一个活性类别( 1
, 2
; 3
-不活动) 3
must be selected, since all its categories are inactive ( 3
, 4
). 3
必须选择,因为它的所有类别是不活动的( 3
, 4
)。 I have the following query, which is obviously incorrect, since it selects both products: 2
and 3
: 我有以下查询,这显然是不正确的,因为它选择了两个产品:
2
和3
:
SELECT p.id_product
FROM product p
JOIN category_product cp
ON p.id_product = cp.id_product
JOIN category c
ON c.id_category = cp.id_category
WHERE
c.active = 0;
Here is the SQL Fiddle: http://sqlfiddle.com/#!2/909dd/2/0 这是SQL小提琴: http ://sqlfiddle.com/#!2/909dd/2/0
How can I solve this? 我怎么解决这个问题?
This way you can select product without active category. 这样您就可以选择没有活动类别的产品。
SELECT p.id_product
FROM product p
WHERE NOT EXISTS
(SELECT * FROM
category_product cp
INNER JOIN category c ON c.id_category = cp.id_category
WHERE p.id_product = cp.id_product AND c.active = 1);
This is what i get while trying...apologies if anything is wrong 这就是我在尝试时得到的......如果出现任何问题,请道歉
set @count:=0;
select a.id_product,a.times from
(SELECT count(p.id_product)times, p.id_product, c.active,
if(c.active!=0, @count:=@count+1, @count:=0) x
From category_product cp
join product p
on (p.id_product = cp.id_product)
join category c
on(c.id_category = cp.id_category )
group by id_product )a
where a.x=0;
Consider the following: 考虑以下:
SELECT p.*
, COUNT(*)
, SUM(c.active = 1) active
, SUM(c.active = 0) inactive
FROM product p
JOIN category_product cp
ON cp.id_product = p.id_product
JOIN category c
ON c.id_category = cp.id_category
GROUP
BY p.id_product;
+------------+----------+--------+----------+
| id_product | COUNT(*) | active | inactive |
+------------+----------+--------+----------+
| 1 | 2 | 2 | 0 |
| 2 | 3 | 2 | 1 |
| 3 | 2 | 0 | 2 |
+------------+----------+--------+----------+
http://sqlfiddle.com/#!2/909dd/55 http://sqlfiddle.com/#!2/909dd/55
The last part of this problem has been left as an exercise for the reader 这个问题的最后一部分留给读者练习
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.