[英]Query two tables ordered by “date” field
我的mySQL數據庫中有兩個表。 這兩個表完全不同,沒有什么共同點,但是它們都有一個“日期”字段。
我想通過PHP從“日期”字段排序的兩個表中獲取所有行。
例:
-----------------------------------------------
name | category | date
-----------------------------------------------
PSO | Food | 2015-09-16
TSI | Sport | 2015-10-12
-----------------------------------------------
-----------------------------------------------
film | date
-----------------------------------------------
Harry Potter | 2015-09-19
Star Wars | 2015-11-14
-----------------------------------------------
我期望的結果是:
PSO, Food, 2015-09-16
Harry Potter, 2015-09-19
TSI, Sport, 2015-10-12
Star Wars, 2015-11-14
我怎樣才能做到這一點?
PS:表格的每一行將是我網頁上的一個div,這些div必須按日期排序。
看起來您在尋找UNION
但結果將與您發布的結果不同; 由於UNION
限制了兩個表必須具有相同的列數,但是您可以為缺少的列插入NULL
,盡管如下所示。
select * from (
select name,
category,
`date` from table1
union
select film, null, `date`
from table2) xx
order by `date`;
嘗試
SELECT name, category, concat('') AS film, date
FROM TABLE_1 ORDER BY `date`
UNION
SELECT concat('') AS name, concat('') AS category, film, date
FROM TABLE_2
ORDER BY `date` ;
由於UNION
希望在執行聯合操作時具有相似的列名,因此您可能需要使用具有空值的自定義列。
select name ,
category,
date from table1
union all
select film as name , null as category , date
from table2
order by date;
確保兩個表的別名相同並正確排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.