简体   繁体   中英

how to get the top 2 updated records of each table in mysql

I have 3 tables (articlestbl, businesstbl, photostbl). Now, I want to fetch the top 2 most updated records for each table in ONLY ONE query. These tables are not related to each other(No foreign keys).Is it possible to do that? if so, how to do that. thanks.

articlestbl

art_id  art_description   art_date
  1       article1           2014-06-02
  2       article2           2014-06-01
  3       article3           2014-06-02

businesstbl

bus_id  bus_description      bus_date
  1       business1           2014-05-09
  2       business2           2014-06-01
  3       business3           2014-06-02

photostbl

p_id    p_description      p_date
  1       photos1           2014-05-09
  2       photos2           2014-04-01
  3       photos3           2014-03-02

The row result should be

article1
article3
business2
business3
photos1
photos2

Use UNION ALL :

SELECT * FROM articlestbl ORDER BY art_date DESC LIMIT 2
UNION ALL SELECT * FROM businesstbl ORDER BY bus_date DESC LIMIT 2
UNION ALL SELECT * FROM photostbl ORDER BY p_date DESC LIMIT 2

But the fact that you need to read from three different tables can be a hint to a design problem. What you do here looks like Class Table Inheritance , consider looking into Single Table Inheritance which is more efficient

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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