Abenil
Abenil

Reputation: 1158

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  |
+----+-------------+

Upvotes: 1

Views: 626

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269743

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.

Upvotes: 1

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

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)

Upvotes: 1

Related Questions