3

好的,到这里,我有 3 张桌子:

accounts             ( account_id,      employee_id, account_name )
projects             ( project_id,      project_name )
project_distribution ( distribution_id, employee_id, project_id )

如果我有 project_distribution 表中的项目 ID,我想要做的是从项目表中返回项目名称。所以,假设我有 employee_id,我将进入 project_distribution 并进行选择,我得到 2 个值对于 project_id ,id 1 和 2,我如何在不执行 2 个查询或语句或如何正确调用它们的情况下返回这两个 ID 的 project_names,这是我的错误选择语句。

SELECT project_name
FROM   projects
WHERE  project_id = ( SELECT project_id
                      FROM   project_distribution
                      WHERE  employee_id = ( SELECT employee_id
                                             FROM accounts
                                             WHERE account_name = 'tbogdan'
                                            )
                    );

oufcorse 我将从 project_distribution 中获得 2 个值,并且出现“子查询返回超过 1 个值”错误我该如何解决这个问题并让它工作?如果需要更多信息,请询问...抱歉描述模糊...

4

4 回答 4

1

尝试这样的事情......

SELECT projects.project_name 
FROM projects
INNER JOIN project_distribution ON (projects.project_id = project_distribution.project_id)
INNER JOIN accounts ON (project_distribution.employee_id = accounts.employee_id)
WHERE accounts.employee_id = 'tbogdan'
于 2012-06-03T13:04:34.300 回答
1

在 project_distribution 子查询中使用 IN 关键字而不是 equals。

SELECT project_name
FROM   projects
WHERE  project_id = ( SELECT project_id
                      FROM   project_distribution
                      WHERE  employee_id IN ( SELECT employee_id
                                             FROM accounts
                                             WHERE account_name = 'tbogdan'
                                            )
                    );

您可以通过手动输入您希望从子查询返回的值来测试没有子查询的查询:

SELECT project_name
FROM   projects
WHERE  project_id IN (1,2)
于 2012-06-03T13:10:36.637 回答
0
SELECT projects.project_name
FROM   projects
INNER JOIN project_distribution distrib
    ON projects.project_id = distrib.project_id
INNER JOIN accounts
    ON distrib.employee_id = accounts.employee_id
WHERE accounts.account_name = 'tbogdan';
于 2012-06-03T13:04:36.387 回答
0

EXISTS 也是一种可能性:

SELECT pr.project_name
FROM   projects pr
WHERE  EXISTS (
    SELECT * 
    FROM project_distribution pd
    JOIN accounts ac ON ac.employee_id = pd.employee_id
    WHERE ac.account_name = 'tbogdan'
    );

存在的好处是内部相关名称 (pd,ac) 不会暴露给主查询。

于 2012-06-03T13:51:29.140 回答