我有这张桌子:

CREATE TABLE `test1` (
  `id` int(4) NOT NULL,
  `company_Id_Company` varchar(10) NOT NULL,
  `head_Id_Head` int(4) NOT NULL,
  `detail_Id_Detail` int(4) NOT NULL,
  PRIMARY KEY (`id`,`company_Id_Company`,`head_Id_Head`),
  KEY `fk_test1_detail` (`id`,`head_Id_Head`,`detail_Id_Detail`),
  CONSTRAINT `fk_test1_detail` FOREIGN KEY (`id`, `head_Id_Head`, `detail_Id_Detail`) REFERENCES `detail` (`id`, `head_Id_Head`, `id_Detail`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_test1_company` FOREIGN KEY (`id`, `company_Id_Company`) REFERENCES `company` (`id`, `id_Company`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB

我把这些数据放在表中:
 id | company_Id_Company | head_Id_Head | detail_Id_Detail
-----------------------------------------------------------
 1            01                1                7
 1            02                1                7
 1            01                3                2
 1            03                2                9
 1            05                4                1
 1            01                5                4
 1            02                5                4
 1            03                5                4

我需要同时找到满足两个强制条件的所有数据:
select * from test1 where head_Id_Head = 1 and detail_Id_Detail = 7
                 AND
select * from test1 where head_Id_Head = 5 and detail_Id_Detail = 4

如果这两个查询正在运行,我应该是compañoa:01和02
我怎么能提出这个问题?

最佳答案

这会假设你没有副本。。

SELECT  *
FROM    test1 t1
WHERE   [company_Id_Company] IN (SELECT [company_Id_Company]
                                 FROM   test1 t2
                                 WHERE  ((t2.head_Id_Head = 1
                                              AND t2.detail_Id_Detail = 7)
                                             OR (t2.head_Id_Head = 5
                                                 AND t2.detail_Id_Detail = 4))
                                 GROUP BY t2.[company_Id_Company]
                                 HAVING COUNT(*) = 2)

关于mysql - 多选同一张表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35583515/

10-12 16:26