从两个不同的表中选择并按一个顺序排序并限制另一个的结果?

时间:2017-01-04 14:44:34

标签: mysql select

请有人帮忙。

我有两个表,car_table和add_table,它们是完全不同的表。

car_table:

+---------+-------------+------+-----+------------------+----------------+
| Field   | Type        | Null | Key | Default          | Extra          |
+---------+-------------+------+-----+------------------+----------------+
| id      | int(3)      | NO   | PRI | NULL             | auto_increment |
| car     | varchar(15) | NO   |     | NULL             |                |
| manuf   | varchar(10) | NO   |     | NULL             |                |
|timestamp| timestamp   | NO   |     | CURRENT_TIMESTAMP|                |
+-------+-------------+------+-----+---------+---------------------------+

示例数据:

+----+--------+-------+-----------+
| id | car    | manuf | timestamp | 
+----+--------+-------+-----------+
|  1 | M5     | BMW   | time      |
|  2 | Golf   | VW    | time      | 
|  3 | Toyota |pickup | time      |
|  4 | Ford   | focus | time      |
+----+--------+-------+-----------+

add_table

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
|add_id | int(3)      | NO   | PRI | NULL    | auto_increment |
| link  | varchar(15) | YES  |     | NULL    |                |
| s_img | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

示例数据:

+-------+--------+-------+
|add_id | link   | s_img |
+-------+--------+-------+
|  1    | link   | img   |
|  2    | link   | img   | 
|  3    | link   | img   | 
|  4    | link   | img   | 
+-------+--------+-------+

我正在尝试编写一个select语句,它将按时间戳对car_table进行排序,并将add_table限制为3个结果,混合结果,以便add_table结果由car_table结果分隔。

以下是我目前的情况,但不知道从哪里开始。 (更新:这似乎部分有效,但不确定它是什么订购add_table并且不确定它是否是正确的方法。)

SELECT  id,car,manuf,timestamp,
FROM car_table
UNION ALL
SELECT add_id,link,s_img,NULL AS timestamp
FROM add_table ORDER BY TimeStamp

0 个答案:

没有答案