union all
select *,'1' as category from table1001 where price > 10
union all
select *,'2' as category from table1002 where price > 10
union all
select *,'3' as category from table1003 where price > 10
order by ID
列的個數要保持一致,列名可以不一樣,但是對應的列的數據類型要一樣。同樣可以使用order by,limit這些。
例如對於大數據的橫向分表后,可以使用此方法查詢。
如果其中某個表新增了字段,可以改為查詢固定的字段進行 union all.例如:
select id,name,age from table1001 where price > 10 union all select id,name,age from table1002 where price > 10 union all select id,name,age from table1003 where price > 10 order by ID
參考:
http://bbs.51cto.com/thread-1076108-1-1.html
MySQL使用select查詢時,在查詢結果中增加一個字段並指定固定值
假設需求是這樣的:
1
2
3
4
5
6
7
8
|
mysql> desc user;
+-------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | char(30) | NO | | NULL | |
+-------+----------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
|
假設user表中,有id和name兩個字段,現在需要查詢user表中所有數據,並增加一個字段(is_person),判斷該記錄所描述的是不是一個人?
別去鑽牛角尖,很明顯,is_person的值始終為true,那么在查詢的時候,就可以在返回結果中新增一個字段is_person,並指定值為true。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
mysql> select * from user;
+----+------+
| id | name |
+----+------+
| 1 | abc |
| 2 | xyz |
+----+------+
2 rows in set (0.00 sec)
mysql> select *,
"true"
as
is_person from user;
+----+------+-----------+
| id | name | is_person |
+----+------+-----------+
| 1 | abc | true |
| 2 | xyz | true |
+----+------+-----------+
2 rows in set (0.00 sec)
|
注意上面的格式,使用關鍵字as,這里的as和平時使用的as代表的意思是相同的!!!
平常使用as是為字段取一個別名,as的左邊是一個原始字段名,右邊是新的別名,該別名會顯示在查詢結果中,而原始字段名代表的就是該字段的值;
此處為新增字段指定固定值,as的左邊為新增字段的固定值,右邊才是新增字段的字段名,此時字段名不用加引號,如果固定值為數值型則不用加引號,如果固定值為其他類型則必須加引號。