简体   繁体   中英

Get results from multiple rows with same names

I have some tables with various content. What I want to accomplish is to display the lets say 20 latest entries from those tables in a div.

Here is my first table - audio1

userID folder title date

the two other folders look exactly the same

audio2

userID folder title date

audio3

userID folder title date

How can I get the data from all the tables at the same time and echo them one by one to a div ordered by date with PHP?

SELECT userID, folder, title, date
    FROM audio1
UNION ALL
SELECT userID, folder, title, date
    FROM audio2
UNION ALL
SELECT userID, folder, title, date
    FROM audio3
ORDER BY date DESC LIMIT 20;

Your SQL query will be a 3 part UNION . A UNION query concatenates results from multiple tables with (usually) similar structures, when a JOIN relationship is not needed but rather you just need to return rows from multiple tables.

$sql = "SELECT userID, folder, title, date FROM audio1
  UNION ALL
  SELECT userID, folder, title, date FROM audio2
  UNION ALL
  SELECT userID, folder, title, date FROM audio3
  LIMIT 20;";

$result = mysql_query($sql);
if ($result) {
  // Fetch results and echo them into a list.
}

You will need a column to ORDER BY . This is likely to be date , but you may have other plans. Add an ORDER BY clause before the LIMIT 20 .

看来您的数据库设置是错误的,您只需要一个名为“ audio”的表,其中一个字段表示表名中当前正在使用的数字。

You may try the union, or you can try a join.

SELECT 
  COALESCE(t1.userID, t2.userID, t3.userID) as userID 
           , t1.folder, t1.title, t1.date
           , t2.folder, t2.title, t2.date  
           , t3.folder, t3.title, t3.date  
FROM table1 t1
FULL OUTER JOIN table2 t2 ON (t1.userID = t2.userID)
FULL OUTER JOIN table3 t3 ON (t1.userID = t3.userID)  

It's a very different beast, so I'd thought I'd give you the option.

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