0

我正在尝试创建一个查询,该查询显示 TableA 中的 a4、a2、a3 和 TableC 中由 b.b1 = 2 连接的所有项目的日期。输出应按日期降序按时间顺序排列。

TableA                 
___________________________________________
| a1   | a2   | a3   | a4   | a5   | a6   |
-------------------------------------------
| 1    |  222 | 333  | 444  | 555  | 665  |
-------------------------------------------
| 2    |  asd | sdf  | ert  | jkl  | xcv  |
-------------------------------------------
| 3    |  111 | tyu  | bnm  | abc  | xyz  |
-------------------------------------------
| 4    |  222 | yyy  | dfd  | hgg  | 544  |
-------------------------------------------  
| 5    |  222 | y56  | df5  | hg7  | 234  |
------------------------------------------- 

TableB
___________________
| b1  | b2  | b3  |
-------------------
| 1   | 717 | c   |
------------------- 
| 2   | 727 | d   |
------------------- 
| 3   | 737 | c   |
------------------- 
| 4   | 747 | d   |
------------------- 

TableC - c2 is foreign key to a.a1 - c3 is foreign key to b.b1
_____________________________
| c1  | c2  | c3  |  date   |
-----------------------------
| 1   | 2   | 2   |12-01-12 | 
-----------------------------
| 2   | 1   | 1   |12-05-12 | 
-----------------------------
| 3   | 5   | 2   |12-07-12 | 
-----------------------------
| 4   | 3   | 1   |12-14-12 | 
-----------------------------
| 5   | 4   | 2   |12-18-12 | 
-----------------------------

它应该看起来像这样......

____________________________
| a4  | a2  | a3  |  date  |
----------------------------
| ert | 222 | 333 |12-01-12| 
----------------------------
| df5 | 222 | y56 |12-07-12| 
----------------------------
| dfd | 222 | yyy |12-18-12| 
----------------------------

我明白了,如果我将查询分成两部分,我会从两个表中获取信息,并且“UNION ALL”使我的日期在表的底部添加行(还有另外两列我不想要, c2 和 c1),我实际上想要在我的结果中的 a3 旁边有一个名为 date 的列。如何将该列“日期”放入结果集中?

SELECT a.a4, a.a2, a.a3
FROM TableA a
JOIN TableC c ON c.c2 = a.a1
JOIN TableB b ON b.b1 = c.c3 and c.c3 = 2
UNION ALL
SELECT d.date,d.c2,d.c1 
From TableC d
JOIN TableB b ON b.b1 = d.c3 and d.c3 = 2

请提出任何您需要的问题,这正在杀死我。

4

1 回答 1

2

这里还有其他令人困惑的项目,但无需深入挖掘,这很容易:

SELECT a.a4, a.a2, a.a3, c.date
FROM TableA a
JOIN TableC c ON c.c2 = a.a1
JOIN TableB b ON b.b1 = c.c3 and c.c3 = 2

UNION不做你认为它做了。

另外,是否需要加入表b?

SELECT a.a4, a.a2, a.a3, c.date
FROM TableA a
JOIN TableC c ON c.c2 = a.a1 and c.c3 = 2
于 2013-02-13T21:21:50.033 回答