我在mysql数据库中有三个表:
单位 [id,部分,标题,说明,房间,价格,已更新]
房屋 [ID,部分,标题,说明,房间,价格,已更新]
土地 [id,section,title,description,area,price,updated]
我需要在一个查询(id,title)中检索这些表中所有记录的四条最新记录,而且我不知道如何正确编写查询。我试过这个:
SELECT
flats.id, flats.title, houses.id, houses.title, lands.id, lands.title
FROM
flats, houses, lands
ORDER BY
updated DESC
LIMIT
3
感谢所有回复。
答案 0 :(得分:3)
您可以使用union all
运算符来" concat"结果,然后使用limit
子句获得前四名:
SELECT id, title
FROM (SELECT id, title, updated FROM flats
UNION ALL
SELECT id, title, updated FROM houses
UNION ALL
SELECT id, title, updated FROM lands) t
ORDER BY updated DESC
LIMIT 4
编辑:
正如迈克尔和约翰在评论中指出的那样,子查询是多余的:
SELECT id, title, updated FROM flats
UNION ALL
SELECT id, title, updated FROM houses
UNION ALL
SELECT id, title, updated FROM lands
ORDER BY updated DESC
LIMIT 4
答案 1 :(得分:1)
SELECT
flats.id, flats.title, houses.id, houses.title, lands.id, lands.title
FROM
flats
CROSS JOIN houses
CROSS JOIN lands
ORDER BY
updated DESC
LIMIT
3
但这不是好策略:我猜,如果你应该这样做
答案 2 :(得分:0)
在MySQL中,最常见的方法是使用UNION
语句。
所以,在你的情况下:
(SELECT id,title from flats ORDER BY updated DESC LIMIT 4)
UNION
(SELECT id,title from houses ORDER BY updated DESC LIMIT 4)
UNION
(SELECT id,title from lands ORDER BY updated DESC LIMIT 4);