首先,这是我没有创建且无法更改的数据库设置(Access 2010):
违反:
包装:
我想在给定的Role1和Role2匹配记录时选择WorkPackageCodes。例如,如果Role1为3而Role 2为8,我希望WorkPackageCodes的ID为3和8.例如,Role1为4,Role2为6,则不应选择任何一个。
我通过多个查询实现了这一点,但我想在一个查询中使用它(使用/不使用子查询)。所以我需要一些东西,我可以让我们看看WorkPackageID是否在另一个表的结果集中。我试过这个:
//3 and 6 will be replaced by parameters
SELECT Role1 AS role FROM tblSODViolations
UNION
SELECT Role2 FROM tblSODViolations
WHERE Role1 = 3 AND Role2 = 6
这给了我想要的结果,我试着做一个查询,如下:
SELECT WorkPackageCode
FROM tblWorkPackages
WHERE WorkPackageID IN (SELECT Role1 AS r FROM tblSODViolations
UNION ALL
SELECT Role2 FROM tblSODViolations
WHERE Role1 = 3 AND Role2 = 6);
但是,如果我运行这个,我收到消息:
子查询中不允许执行此操作。
那我怎么能做到这一点?或者有没有办法在某种SQL if语句中选择WorkPackageCode?提前谢谢!
答案 0 :(得分:2)
尝试将其作为联接:
SELECT WorkPackageCode
FROM tblWorkPackages wp join
tblSODViolations v
on wp.WorkPackageID in (v.Role1, wp.WorkPackageId = v.Role2) and
v.Role1 = 3 and v.Role2 = 6;
这可能会产生重复。如果是的话,
SELECT distinct WorkPackageCode
FROM tblWorkPackages wp join
tblSODViolations v
on wp.WorkPackageID in (v.Role1, wp.WorkPackageId = v.Role2) and
v.Role1 = 3 and v.Role2 = 6;
但是,我不清楚为什么这不起作用:
SELECT WorkPackageCode
FROM tblWorkPackages wp
WHERE wp.WorkPackageID in (3, 6);
您也可以这样写:
SELECT WorkPackageCode
FROM tblWorkPackages wp
WHERE wp.WorkPackageID in (3, 6) and
exists (select 1 from tblSODViolations where Role1 = 3 and Role2 = 6)
此特定版本最接近您描述所需内容的方式。
答案 1 :(得分:1)
将联合创建为内联表,并使用它来限制结果。
SELECT WorkPackageCode
FROM tblWorkPackages WP
INNER JOIN
(SELECT Role1 AS r FROM tblSODViolations
UNION ALL
SELECT Role2 FROM tblSODViolations
WHERE Role1 = 3 AND Role2 = 6) B
on B.R = WP.WorkPackageID;
...替代地
Select workpackageCode
FROM tblWorkPackages WP
INNER JOIN tblSODViolations V on V.WorkPackageID=WP.Role1
OR V.workPackageID=WP.Role2
WHERE V.Role1=3 and V.Role2=6