简体   繁体   English

如何从n个表中只获取n条记录

[英]How to get only n records from n tables

I have 3 tables with different content which all have datetime column. 我有3个不同内容的表,都有datetime列。

I want to get last 10 records by datetime DESC from any of 3 tables. 我希望从3个表中的任何一个表中获取datetime DESC的最后10条记录。

Maybe 5 records from table 1, 3 records from table2, and 2 records from table3 表1中有5条记录,表2中有3条记录,表3中有2条记录

How can I do that in mysql. 我怎么能在mysql中做到这一点。 Should I use Union ? 我应该使用Union吗?

I tried both these queries: 我尝试了这两个查询:
Query1: 查询1:

SELECT table1.*, table2.*, table3.* FROM table1, table2, table3 LIMIT 10

Query2: QUERY2:

( SELECT * FROM table 1 LIMIT 10 )
UNION
( SELECT * FROM table 2 LIMIT 10 )
UNION
( SELECT * FROM table 3 LIMIT 10 )

but these queries returns 30 records. 但这些查询返回30条记录。

you have to write separately as you need separate limit 你必须单独写,因为你需要单独的限制

(IF having same columns) (如果有相同的列)

SELECT * FROM table1 limit 5
UNION ALL
SELECT * FROM table2 limit 3
UNION ALL
SELECT * FROM table3 limit 2

UPDATE: 更新:

//if we need 10 rows in the result
SELECT * FROM table1,table2,table3 limit 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM