Search code examples
mysqltemp-tables

MYSQL QUERY for Products and Variants


I was hoping I could get some help with a Query I am trying to figure out. Our online store needs to know when all variants of a product are at quantity zero so we can disable the product from customer view. The table I am working with is just the variant table.

we'll call it cart_variants

| variantid | productid | avail |
| 5677      |   1310    |   0   |
| 5399      |   1310    |   2   |
| 5228      |   1223    |   0   |
| 5133      |   1223    |   0   |

I need to return all productids who's variant quantities are all zero. Product ids can have any amount of variants. In the example above the query would only return productid 1223.

I'm pretty sure this is not a really complex query but it sure has kicked me butt. As close as I've been able to come was:

SELECT productid, SUM(avail)as qty FROM 'cart_variants' GROUP BY productid

That gives me the list of all products and their qtys but I cant figure out how to get it into a temp table and query the productid with qty = 0.

Most of the examples working with temp tables and select queries are not very clear. I tried several incarnations and none of them worked to completion.

Any help is appreciated.


Solution

  • Assuming that you'd never have a negative avail value, you really only need to apply a HAVING clause to your query:

    SELECT c.productid
        FROM cart_variants c
        GROUP BY c.productid
        HAVING SUM(c.avail) = 0