[英]MySQL nested Select statement with subquery
I am struggeling with a database query for 2 Hours now. 我正在努力进行2小时的数据库查询。 There is the following database structure: article table
数据库结构如下:文章表
+---------------+-------------+
| id | ordernumber |
+---------------+-------------+
| 1 | 3243 |
| 2 | 3344 |
| 3 | 3423 |
| 4 | 7687 |
+---------------+-------------+
variant table 变型表
+----+-----------+-------+-------+
| id | articleId | stock | price |
+----+-----------+-------+-------+
| 1 | 1 | 3 | 10,99 |
| 2 | 1 | 0 | 10,99 |
| 3 | 1 | 1 | 10,99 |
| 4 | 2 | 0 | 11,99 |
| 5 | 2 | 0 | 11,99 |
| 6 | 2 | 1 | 11,99 |
+----+-----------+-------+-------+
I want to get all Articles where all but one variant have 0 stock. 我想获得所有文章,其中除一个变体外所有其他都具有0库存。 Is this even possible with a plain sql statement?
使用普通的sql语句甚至可能吗? I tried with a subquery, but without success, since the subquery gets executed first and I would need to pass values from the current record of the resultset of the outer query.
我尝试了一个子查询,但是没有成功,因为该子查询首先执行,并且我需要传递外部查询结果集的当前记录中的值。
Any help is much appreciated. 任何帮助深表感谢。
Edit: Expected Result: 编辑:预期结果:
+----+-------------+
| id | ordernumber |
+----+-------------+
| 2 | 3344 |
+----+-------------+
This can be done using group by
and having
. 可以使用
group by
和having
来完成。
select articleID
from variants
group by articleID
having count(*) - 1 = count(case when stock = 0 then 1 end)
If you want the full information for the variant: 如果您需要有关变体的完整信息,请执行以下操作:
select v.*
from variants v
where v.stock > 0 and
not exists (select 1
from variants v2
where v2.articleID = v.articleID and
v2.stock > 0 and
v2.id <> v.id
);
Note: this assumes that the duplicated "5" is a typo and that the ids really are unique in the table. 注意:这假定重复的“ 5”是错字,并且id在表中确实是唯一的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.