爲了將所有的數據和日期倒序排序,你可以使用一個子查詢與UNION ALL
並從所有3個表結合聯合國下令結果...然後命令由時間戳下降的記錄。下面是一個例子。但是,如果它們都具有不同的字段名稱並且字段名稱的數量不同,則可以創建虛擬字段名稱以創建一致的信息。它在下面的編輯中被描述。
爲了簡單起見,我們假設所有表的構造如下
+-------+-----------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+-------------------+-------+
| id | int(11) | YES | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | |
+-------+-----------+------+-----+-------------------+-------+
讓我們來看看每個表中的虛擬數據。
產品
mysql> select * from products;
+------+---------------------+
| id | ts |
+------+---------------------+
| 1 | 2014-03-26 04:39:06 |
| 4 | 2014-03-26 04:40:05 |
+------+---------------------+
User_Purchased
mysql> select * from user_purchased;
+------+---------------------+
| id | ts |
+------+---------------------+
| 2 | 2014-03-26 04:39:19 |
| 5 | 2014-03-26 04:40:00 |
+------+---------------------+
交貨
mysql> select * from delivery;
+------+---------------------+
| id | ts |
+------+---------------------+
| 3 | 2014-03-26 04:39:28 |
| 6 | 2014-03-26 04:39:38 |
+------+---------------------+
PHP
<?php
$db = mysqli_connect('host','usr','pwd');
mysqli_select_db($db,'yourdb');
$data = mysqli_query($db, "
select * from
(
select 'products' as tbl, id, ts from products
union all
select 'purchased' as tbl, id, ts from user_purchased
union all
select 'delivered' as tbl, id, ts from delivery
) a
order by ts desc
"
);
echo "tablename\tid\ttime\n";
foreach ($data as $row) {
echo "{$row['tbl']}\t{$row['id']}\t{$row['ts']}\n";
}
?>
輸出
tablename id time
products 4 2014-03-26 04:40:05
purchased 5 2014-03-26 04:40:00
delivered 6 2014-03-26 04:39:38
delivered 3 2014-03-26 04:39:28
purchased 2 2014-03-26 04:39:19
products 1 2014-03-26 04:39:06
編輯
假設產品表有字段標識,產品名稱,productnumber。 購買了id,productid,purchaseate。 交付有id,purchaseid,deliverydate。
你可以通過做這樣的事情在每個查詢中的所有字段組合,然後排序上mytimestamp:
select
'products' as tbl, pdt_id, productname as pdt_productname, productnumber as pdt_productnumber,
'-' as pur_id, '-' as pur_productid, '-' as pur_purchasedate,
'-' as del_id, '-' as del_purchaseid, '-' as del_deliverydate,
ts as mytimestamp
from products
union all
select
'purchased' as tbl, '-' as pdt_id, '-' as pdt_productname, '-' as pdt_productnumber,
id as pur_id, productid as pur_productid, purchasedate as pur_purchasedate,
'-' as del_id, '-' as del_purchaseid, '-' as del_deliverydate,
ts as mytimestamp
from purchased
union all
select
'delivered' as tbl, '-' as pdt_id, '-' as pdt_productname, '-' as pdt_productnumber,
'-' as pur_id, '-' as pur_productid, '-' as pur_purchasedate,
id as del_id, purchaseid as del_purchaseid, deliverydate as del_deliverydate,
ts as mytimestamp
from delivered
「從由時間戳倒序產品訂單*;」分號裏面? –
@ M.chaudhry yes – jason
@ M.chaudhry:';'分號在引號內作爲stmt終結符是合法的。 –