我有这张桌子:
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
我如何进行此查询?
答案 0 :(得分:3)
您可以OR
而不是AND
:
select your_table.company_Id_Company from your_table inner join (
select company_Id_Company from your_table where head_Id_Head = 5
AND detail_Id_Detail = 4) as temp on temp.company_Id_Company your_table.company_Id_Company
where head_Id_Head = 1 AND detail_Id_Detail = 7
答案 1 :(得分:2)
您可以INNER JOIN两个结果集
select
from test1 AS T1
INNER JOIN (select * from test1 where head_Id_Head = 5 and detail_Id_Detail = 4) AS T2
ON T2.company_Id_Company = T1.company_Id_Company
where T1.head_Id_Head = 1 and T1.detail_Id_Detail = 7
甚至更简单
select *
from test1
where head_Id_Head = 1 and detail_Id_Detail = 7
AND company_Id_Company IN (select company_Id_Company from test1 where head_Id_Head = 5 and detail_Id_Detail = 4)
答案 2 :(得分:2)
这会假设你没有重复..
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)