SQL Select - 根据另一个表中的ID返回两次相同的列

时间:2016-03-04 16:25:28

标签: sql sql-server

我说下面的表格(ID& ID2分别是PK / FK),我如何设计一个两次提取detailTable.name列的查询,每个一次第一个表中的ID

我想要的结果集如下:

+------+--------+------+---------+
| Name | Name 2 | Code | Created |
+------+--------+------+---------+
| Dave | Steven | AAAA | 1/10/10 |
+------+--------+------+---------+

我尝试使用两个连接执行此操作,但不断收到此错误:

SELECT 
       DT.name as [Name 1], 
       DT.name as [Name 2]
       --other columns would go here

FROM linkTable LT 

LEFT JOIN
     detailTable DT
     ON LT.id2 = DT.id 
LEFT JOIN
     linkTable LT2
     ON LT2.id = DT.id
where DT.id = '74'

错误:将数据类型nvarchar转换为bigint时出错

linkTable

+-----+-------+--------+-------------------------+-----------+
| ID  | ID2   | Code   | Created                 | CreatedBy |
+-----+-------+--------+-------------------------+-----------+
| 76  | 15157 | AAAA   | 1/1/10                  | 844       |
+-----+-------+--------+-------------------------+-----------+
| 77  | 15340 | AAAA   | 2015-11-24 15:12:25.057 | 842       |
+-----+-------+--------+-------------------------+-----------+
| 94  | 14644 | GEOFA  | 2015-11-13 15:01:19.977 | 842       |
+-----+-------+--------+-------------------------+-----------+
| 94  | 16346 | XX2222 | 2015-11-13 15:01:57.290 | 842       |
+-----+-------+--------+-------------------------+-----------+
| 108 | 15966 | EMPE   | 2015-11-25 12:38:37.377 | 842       |
+-----+-------+--------+-------------------------+-----------+

detailTable

+-------+----------+
| ID    | Name     |
+-------+----------+
| 76    | Dave     |
+-------+----------+
| 15157 | Steven   |
+-------+----------+
| 94    | Roger    |
+-------+----------+
| 108   | Geoff    |
+-------+----------+
| 16346 | Penelope |
+-------+----------+
| 15966 | Paul     |
+-------+----------+
| 77    | Michael  |
+-------+----------+
| 14644 | Colin    |
+-------+----------+
| 15340 | Nigel    |
+-------+----------+

谢谢:)

2 个答案:

答案 0 :(得分:1)

在正常情况下,不需要left join,因为链接表应该只有有效的引用。标签指出,原始查询中的逻辑不正确。

我唯一的猜测是'74'不是真正的两位数 - 隐藏的字符或其他一些问题。在任何情况下,整数常量都不需要单引号,因此您可以尝试:

SELECT DT1.name as [Name 1], 
       DT2.name as [Name 2]
       --other columns would go here
FROM linkTable LT JOIN
     detailTable DT1
     ON LT.id1 = DT1.id JOIN
     detailTable DT2
     ON LT.id2 = DT2.id
WHERE DT.id = 74;

如果这不能解决问题,我会质疑所有id列都是bigint的断言。如上所述,查询没有其他可能发生此类型转换的地方。

答案 1 :(得分:0)

您想要两次加入Detail表,而不是Link表:

SELECT 
       DT.name as [Name 1], 
       DT2.name as [Name 2]
       --other columns would go here

FROM linkTable LT 

LEFT JOIN
     detailTable DT
     ON LT.id = DT.id 
LEFT JOIN
     detailTable DT2
     ON LT.id2 = DT2.id
where LT.id = '74'

如果您仍然使用此格式获得转换错误,则可能是在"其他列中的一个"你没有在你的例子中展示。