如何使用两个子查询从两个表中提取值? T-SQL

时间:2017-02-15 23:34:30

标签: sql sql-server tsql subquery

首先,如果我问完全错误的问题,我想道歉 - 我是初学者,当涉及到SQL而我不确定如何实现我的目标,但我假设我的研究基于子查询是我需要使用的。

我有两个表,一个有时间卡数据(表1),另一个有高级项目数据(表2)。

表1

+------+------------------+---------------+-------------+
| code | work_description | resource_name | total_hours |
+------+------------------+---------------+-------------+
|  101 | Time Reporting   | Jane Doe      |           5 |
|  101 | Time Reporting   | Jane Doe      |           7 |
|  101 | Time Reporting   | Jane Doe      |           9 |
|  201 | Time Reporting   | Joe Smith     |           2 |
|  201 | Time Reporting   | Joe Smith     |           4 |
|  201 | Time Reporting   | Joe Smith     |           6 |
+------+------------------+---------------+-------------+

表2

+------+------------+----------------+
| code | project_id |     descr      |
+------+------------+----------------+
|  100 |        100 | Project A      |
|  101 |        100 | Time Reporting |
|  102 |        100 | Milestones     |
|  103 |        100 | Planning       |
|  200 |        200 | Project B      |
|  201 |        200 | Time Reporting |
|  202 |        200 | Milestones     |
|  203 |        200 | Planning       |
+------+------------+----------------+

在表2中,当代码列等于project_id列时,descr显示项目名称。除了与每行对应的项目名称之外,我还需要提取表1中的所有内容。

我需要什么:

+-----------+------+------------------+---------------+-------------+
|  descr    | code | work_description | resource_name | total_hours |
+-----------+------+------------------+---------------+-------------+
| Project A |  101 | Time Reporting   | Jane Doe      |           5 |
| Project A |  101 | Time Reporting   | Jane Doe      |           7 |
| Project A |  101 | Time Reporting   | Jane Doe      |           9 |
| Project B |  201 | Time Reporting   | Joe Smith     |           2 |
| Project B |  201 | Time Reporting   | Joe Smith     |           4 |
| Project B |  201 | Time Reporting   | Joe Smith     |           6 |
+-----------+------+------------------+---------------+-------------+

我的过程是首先我必须找到与表1中每行相关的project_id。然后,我可以使用该值来匹配表2中的project_id,因此我可以将项目名称拉出descr专栏

这是我到目前为止所拥有的。这正确地拉出项目ID(我不知道这是否是最佳做法)。我已经为项目名称尝试了几个不同的子查询,但我还没能做到。

SELECT  
    (SELECT t2.code WHERE t1.code=t2.code) as found_project_id,
    t2.descr,
    t1.code,
    t1.work_description,
    t1.resource_name,
    t1.total_hours
FROM Table1 as t1   
    INNER JOIN Table2 as t2 ON t1.code=t2.code

所以我的问题是,除了项目名称之外,我如何使用子查询(或任何其他方法)来提取所有表1?

1 个答案:

答案 0 :(得分:1)

你不需要这里的子查询。一个简单的连接就足够了,因为内连接已经完成了你试图用子查询做的事情:

SELECT
    proj.descr,
    t2.code,
    t1.work_description,
    t1.resource_name,
    t1.total_hours
FROM table2 t2

JOIN table1 t1 ON
    t1.code = t2.code
JOIN table2 proj ON
    proj.code = t2.project_id