简体   繁体   中英

MySQL nested Select statement with subquery

I am struggeling with a database query for 2 Hours now. 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. Is this even possible with a plain sql statement? 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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