我有下表,我试图从使用MySQL中选择数据:
INSERT INTO `test` (`id_location`, `id_sector`, `id_group`) VALUES
(1, 1, 2),
(2, 1, 2),
(3, 1, 3),
(4, 3, 3),
(5, 2, 4),
(6, 3, 4),
(7, 2, 5),
(8, 1, 5),
我想选择id_sector = 1
所在的行,但我还需要返回具有与查询返回的相同组值的任何行。例如:
SELECT * FROM `test` WHERE `id_sector` = `1`
将返回行id_location
1,2,3和8,但我会遗漏id_location
4和7的行,我需要这些行,因为它们具有相同的id_group
(3和7)
答案 0 :(得分:1)
您应首先获得与您选择的id_sector对应的id_group的明确列表,然后根据该列表进行查询:
SELECT * FROM `test` WHERE `id_group` IN
(SELECT DISTINCT `id_group` FROM `test` WHERE `id_sector` = 1)