我有几张桌子:
这些是我的主表。
我也有一些映射表: 1." CompanyDCMap"包含公司映射到诊断中心的表格 2." InvestigationDCMap"包含诊断中心调查MAPPING(简称DC)的表格
我必须根据以下两个标准过滤一组DC:
我如何为此编写查询,以便获得在CompanyDCMap和InvestigationDCMap中的DC,因为我有" CompanyDetails"的主键。和"调查"表。
我几乎放弃了,我无法想到一个同时过滤两个集合的查询。
请帮帮我。
更新 架构: 公司详细信息表:
CompanyID(PRIMARY KEY), CompanyName(NVARCHAR(100))
1 Company1
2 Company2
3 Company3
调查表:
InvestigationID(Primary key) , InvestigationName(NVARCHAR(100))
1 HIV+ Blood Test
2 TMT
3 Urine Test
DCDetails表:
DCID(PRIMARY KEY), DCName(NVARCHAR(100))
1 DC1
2 DC2
3 DC3
CompanyDCMap表
CompanyDCMapID(Primary key), CompanyID(Foreign key), DCId(Foreign Key)
1 1 1
2 1 2
3 2 2
4 2 3
5 3 1
6 3 3
InvestigationDCMap表
InvestigationDCMapID(Primary Key), InvestigationID(Foreign Key), DCId(Foreign Key)
1 1 1
2 1 3
3 2 2
4 2 3
给定CompanyID = 1且InvestigationID = 2,SELECT DCId和DCName =
的查询的预期输出 DCId(Int) DCName(NVARCHAR(100))
2 DC2
答案 0 :(得分:4)
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
要获得“不同”值,您可以使用:
SELECT DISTINCT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
或者...
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID
GROUP BY d.DCID, d.DCName;
更好的是,因为不需要与其他表的关系:
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
WHERE EXISTS (SELECT 1 FROM dbo.CompanyDCMap WHERE DCId = d.DCID)
AND EXISTS (SELECT 1 FROM dbo.InvestigationDCMap WHERE DCId = d.DCID);
这将是一个更有效的查询,但如果您需要其他表中的其他列,则需要恢复为连接版本。