简体   繁体   English

从具有相同名称的多行中获取结果

[英]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. 我要完成的是在div中显示这些表中的20条最新条目。

Here is my first table - audio1 这是我的第一张桌子-audio1

userID folder title date

the two other folders look exactly the same 其他两个文件夹看起来完全一样

audio2 音频2

userID folder title date

audio3 音频3

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? 如何在同一时间从所有表中获取数据,并用PHP逐一将它们回显到按日期排序的div?

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 . 您的SQL查询将是3部分的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. 当不需要JOIN关系,而是只需要从多个表返回行时, UNION查询将来自具有(通常)相似结构的多个表的结果连接起来。

$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 . 您将需要一列ORDER BY This is likely to be date , but you may have other plans. 这可能是date ,但是您可能还有其他计划。 Add an ORDER BY clause before the LIMIT 20 . LIMIT 20之前添加一个ORDER BY子句。

看来您的数据库设置是错误的,您只需要一个名为“ 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. 这是完全不同的野兽,所以我想我会给你选择的。

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

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