如何使用单个查询显示来自不同表的数据?

时间:2015-08-25 05:24:26

标签: php mysql sql

**How to display the data as below with one query?** //Limit 2 and order by date and date2.

Data from tabel a

|  1 | aaa    | 2014-06-16 16:29:51

Data from tabel b

|  1 | aa2    | 2014-06-16 16:29:52
Table a

+-------+--------+------+-----+---------+----------------+
| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(3)  | YES  |     | NULL    |                |
| date  | datetime    | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Table b

+-------+--------+------+-----+---------+----------------+
| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(3)     | NO   | PRI | NULL    | auto_increment |
| name2 | varchar(3) | YES  |     | NULL    |                |
| date2 | datetime   | YES  |     | NULL    |                |
+-------+------------+------+-----+---------+----------------+

Data Table a

+----+--------+
| ID | name   | date
+----+--------+
|  1 | aaa    | 2014-06-16 16:29:51
|  3 | aba    | 2014-06-16 16:29:52
|  8 | id     | 2014-06-16 16:29:53
| 10 | idr    | 2014-06-16 16:29:55


Data Table b

+----+--------+
| ID | name2   | date2
+----+--------+
|  1 | aa2    | 2014-06-16 16:29:52
|  3 | a2a    | 2014-06-16 16:29:53
|  8 | id2    | 2014-06-16 16:29:53
| 10 | id2    | 2014-06-16 16:29:53

**How to display the data as below with one query?** //Limit 2 and order by date and date2.

Data from tabel a

|  1 | aaa    | 2014-06-16 16:29:51

Data from tabel b

|  1 | aa2    | 2014-06-16 16:29:52

1 个答案:

答案 0 :(得分:0)

据我所知,你想要的东西是:

(SELECT ID, name, date
    FROM TableA
    LIMIT 1)

UNION ALL

(SELECT ID, name2, date2
    FROM TableB
    LIMIT 1)