0

首先,这是我没有创建且无法更改的数据库设置(Access 2010):

违规行为:

违规行为

套餐:

在此处输入图像描述

当给定的 Role1 和 Role2 匹配记录时,我想选择 WorkPackageCodes。例如,如果 Role1 为 3,Role 2 为 8,我想要 ID 为 3 和 8 的 WorkPackageCodes。例如,如果 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?提前致谢!

4

2 回答 2

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)

此特定版本最接近您描述所需内容的方式。

于 2013-08-07T12:27:40.257 回答
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
于 2013-08-07T12:29:01.657 回答