我有一张叫“double_select”的桌子,看起来是这样的:

itemID | orderID | status
------   -------   ------
   1        1       ready
   2        1       ready
   3        1      waiting
   4        2      complete
   5        3       ready
  ...      ...       ...

使用一个SQL命令,我想检索:
所有状态为“就绪”的项目
上面返回的任何orderID的所有其他项
所以在上表片段中,我想返回itemID的1、2、3和5。
我可以这样说:
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`;

但看起来不太干净。有更好的办法吗?
下面是详细的表格,非常感谢,
詹姆斯
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');

最佳答案

子查询示例:

select *
from double_select
where orderID in
    (select orderID
     from double_select
     where `status` = 'ready')

关于mysql - MySQL查询:一张表,两级SELECT。有没有更好的办法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6483276/

10-11 02:11