double select语句问题,返回多行,子查询返回多个值

时间:2012-06-03 12:57:21

标签: sql-server select subquery

好的,好的,我有3张桌子:

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

我想要做的是从项目表中返回项目名称,如果我有项目ID来自project_distribution表。那么,我们假设我有employee_id,我要进入project_distribution并做一个select,I获取project_id,id 1和2的2个值,如何返回这两个ID的project_names而不执行2个查询或状态或如何正确调用它们,这是我的错误选择语句。

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个值,并且“Subquery返回的值超过1”错误如何解决这个问题,并让它工作? 如果需要更多信息,请询问...抱歉模糊描述...

4 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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)

答案 2 :(得分: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';

答案 3 :(得分: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)不会暴露给主查询。