Mysql查询将2个表中的列从一个结果集中获取

时间:2013-02-13 21:18:04

标签: mysql sql join union

我正在尝试创建一个显示来自TableA的a4,a2,a3和日期的查询 所有通过b.b1 = 2连接的项目的TableC输出应该在 时间顺序按日期递减。

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旁边调用日期。如何将该列“日期”添加到结果集中?

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

请问你需要的任何问题,这会让我感到害怕。

1 个答案:

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