I am trying to write a query that looks through all combo_items and only returns the ones where all sub_items that it references have Active=1.
I think I should be able to count how many sub_items there are in a combo_item total and then compare it to how many are Active, but I am failing pretty hard at figuring out how to do that…
My table definitions:
CREATE TABLE `combo_items` (
`c_id` int(11) NOT NULL,
`Label` varchar(20) NOT NULL,
PRIMARY KEY (`c_id`)
)
CREATE TABLE `sub_items` (
`s_id` int(11) NOT NULL,
`Label` varchar(20) NOT NULL,
`Active` int(1) NOT NULL,
PRIMARY KEY (`s_id`)
)
CREATE TABLE `combo_refs` (
`r_id` int(11) NOT NULL,
`c_id` int(11) NOT NULL,
`s_id` int(11) NOT NULL,
PRIMARY KEY (`r_id`)
)
So for each combo_item, there is at least 2 rows in the combo_refs table linking to the multiple sub_items. My brain is about to make bigbadaboom 🙁
I would just join the three tables usually and then combo-item-wise sum up the total number of sub-items and the number of active sub-items:
Of course, instead of using
SUM(1)you could just sayCOUNT(ci.c_id), but I wanted an analog ofSUM(si.Active).The approach proposed assumes
Activeto be 1 (active) or 0 (not active).To get only those combo-items whose all sub-items are active, just add
WHERE si.Active = 1. You could then reject theSUMstuff anyway. Depends on what you are looking for actually:By the way, INNER JOIN ensures that there is at least one sub-item per combo-item at all.
(I have not tested it.)