Mysql仅在选中所有子项时返回一行

时间:2014-02-03 11:10:28

标签: mysql sql

我有这张桌子:

CREATE TABLE `test` (
    `id` VARCHAR(50) NOT NULL,
    `parent` VARCHAR(50) NULL DEFAULT NULL,
    `true` VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    INDEX `FK_test_test` (`parent`),
    CONSTRAINT `FK_test_test` FOREIGN KEY (`parent`) REFERENCES `test` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

我有这些数据:

INSERT INTO `test` (`id`, `parent`, `true`) VALUES
('.', '.', NULL),
('active1', 'if', NULL),
('active2', 'if', NULL),
('check1', 'active1', 'case1'),
('check2', 'active1', 'case2'),
('check5', 'active1', 'case4'),
('check3', 'active2', 'case1'),
('check4', 'active2', 'case3'),
('if', '.', NULL);

我有这个问题:

SELECT a.`parent` FROM test a
INNER JOIN (test b) ON a.`parent` = b.`id` AND b.`parent` = 'if'
WHERE a.`true` IN ('case1','case2', 'case4')
GROUP BY a.`parent`;

在结果集中,我得到active1, active2,但我应该只有active1,因为只有在选中所有子项时我才需要a.parent行。

如果选择了所有子项,我怎样才能获得一行?

1 个答案:

答案 0 :(得分:1)

您可以使用HAVING,只能获得与条件数相同的数量(在这种情况下为2)

SELECT a.`parent` FROM test a
INNER JOIN (test b) ON a.`parent` = b.`id` AND b.`parent` = 'if'
WHERE a.`true` IN ('case1', 'case2')
GROUP BY a.`parent`
HAVING COUNT(a.`parent`) = 2;

一般来说,你可以这样检查计数:

SELECT a.`parent` FROM test a
INNER JOIN (test b) ON a.`parent` = b.`id` AND b.`parent` = 'if'
WHERE a.`true` IN ('case1', 'case2')
GROUP BY a.`parent`
HAVING COUNT(a.`parent`) = 
  (SELECT COUNT(*) FROM test t1 WHERE t1.`parent` = a.`parent`);

SQL Fiddle demo