I’ve got a table called “double_select” that looks like this:
itemID | orderID | status
------ ------- ------
1 1 ready
2 1 ready
3 1 waiting
4 2 complete
5 3 ready
... ... ...
And with one SQL command I want to retrieve:
- all items with status “ready”
- all other items for any orderID returned above
So in the above table snippet, I’d like to return itemID’s 1, 2, 3 & 5.
I can do this with this statement:
SELECT `a`.* FROM `double_select` AS `a`, `double_select` AS `b` WHERE `a`.`status` = "ready" OR (`a`.`status` != "ready" AND `b`.`orderID` = `a`.`orderID` AND `b`.`status` = "ready") GROUP BY `a`.`itemID`;
But it doesn’t seem very clean. Is there a better way of doing this?
Table details are below, thanks a lot,
James
CREATE TABLE `double_select` (`itemID` int(11) NOT NULL auto_increment,`orderID` int(11) default NULL, `status` varchar(128) default NULL, PRIMARY KEY (`itemID`), KEY `Status` (`status`)) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
insert into `double_select`(`itemID`,`orderID`,`status`) values (1,1,'ready'),(2,1,'waiting'),(3,1,'waiting'),(4,2,'complete'),(5,2,'ready'),(6,3,'ready'),(7,3,'ready'),(8,4,'complete'),(9,5,'failed'),(10,6,'complete');
Subquery example: