2012-06-18 129 views
2

快速技術問題-追加查詢

我有兩個查詢輸出一些相同的數據。例如,假設兩個查詢都有X列和Y列,每列都有一行,每列有一些數據。所以,我們在每個查詢中都有單元格X1和單元格Y1。

我將如何去附加兩個查詢,以便仍然有兩列X和Y,但是兩行?

感謝

回答

1
[Your first query] 

UNION 

[Your second query] 
4

你可以使用UNION,但要記住列的數量必須相同:

mysql> select * from test_big; 
+-------------+ 
| id   | 
+-------------+ 
|   10 | 
|   11 | 
| 123456789 | 
| 1234567890 | 
| 12345678901 | 
+-------------+ 
5 rows in set (0.00 sec) 

mysql> select * from test; 
+----+------+ 
| id | name | 
+----+------+ 
| 0 | a | 
| 2 | 3 | 
| 3 | none | 
| 6 |  | 
| 9 | a | 
| 11 | a | 
| 50 | a | 
+----+------+ 
7 rows in set (0.00 sec) 

mysql> select * from test_big union select * from test;; 
ERROR 1222 (21000): The used SELECT statements have a different number of columns 
ERROR: 
No query specified 

但你可以使用相同數量的列修復它

mysql> select * from test_big union select id from test; 
+-------------+ 
| id   | 
+-------------+ 
|   10 | 
|   11 | 
| 123456789 | 
| 1234567890 | 
| 12345678901 | 
|   0 | 
|   2 | 
|   3 | 
|   6 | 
|   9 | 
|   50 | 
+-------------+ 
11 rows in set (0.00 sec)