php mysql 双条件排序,PHP-MySQL联合查询,按2个变量排序
每個表(表1和表2)具有其自己的DATETIME字段.
我正在嘗試捕獲兩個表的ID,并按其DATETIME字段對其進行排序.
例:
Table 1 Table 2
------------ -------------
id | datetime1 id | table1id | datetime2
------------------------ -----------------------
1 | 2014-09-21 20:31:26 1 | 2 | 2014-09-21 20:31:29
2 | 2014-09-21 20:31:27 2 | 3 | 2014-09-21 20:31:30
3 | 2014-09-21 20:31:28
Table 3
------------
id | user
------------------------
2 | phil
3 | nathalie
我的輸出未通過以下查詢正確排序:
SELECT *
FROM (
SELECT
1 AS selection,
table1.id, table1.datetime1,
table2.datetime2
table3.user
FROM Table1
LEFT OUTER JOIN table2
ON table1.id = table2.table1id
LEFT OUTER JOIN table3
ON table1.id = table3.id
UNION ALL
SELECT
2 AS selection,
table1.id, table1.datetime1,
table2.datetime2
table3.user
FROM Table1
INNER JOIN table2
ON table1.id = table2.table1id
INNER JOIN table3
ON table1.id = table3.id
) AS query
ORDER BY table1.datetime1 DESC, table2.datetime2 DESC
所需數(shù)據(jù):
從表2 id:2,1,
從表1 id:3,2,1
因此:2、1、3、2、1
編輯
對于可能要處理冗長而復雜的MySQL請求的人們,請在PhpmyAdmin中嘗試一下!它會告訴您錯誤!
編輯
解決方法:
您真正需要做的是更仔細地考慮架構(gòu).考慮將日期時間列命名為相同的名稱,然后運行如下查詢-http://sqlfiddle.com/#!2/a3b4c/7/0
SELECT selection, id, datetimefoo, user FROM (
SELECT
1 AS selection,
table1.id, table1.datetimefoo,
table3.user
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.table1id
LEFT OUTER JOIN table3
ON table1.id = table3.id
UNION
SELECT
2 AS selection,
table1.id, table1.datetimefoo,
table3.user
FROM table1
INNER JOIN table2
ON table1.id = table2.table1id
INNER JOIN table3
ON table1.id = table3.id
) AS T2
ORDER BY datetimefoo DESC
在SQL提琴中,這會產(chǎn)生與您要查找的結(jié)果更接近的結(jié)果.我仍然不確定為什么您需要在第二個查詢上使用INNER JOINS-在這里您不需要做什么.
SELECT * FROM (
SELECT
1 AS selection,
table1.id, table1.datetimefoo AS sort_date, -- alias on first table's date
table2.datetimebar,
table3.user
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.table1id
LEFT OUTER JOIN table3
ON table1.id = table3.id
UNION
SELECT
2 AS selection,
table1.id, table1.datetimefoo,
table2.datetimebar AS sort_date, -- alias on second table's date
table3.user
FROM table1
INNER JOIN table2
ON table1.id = table2.table1id
INNER JOIN table3
ON table1.id = table3.id
) AS T2
ORDER BY sort_date DESC
標簽:php,sql,mysql
來源: https://codeday.me/bug/20191012/1898765.html
總結(jié)
以上是生活随笔為你收集整理的php mysql 双条件排序,PHP-MySQL联合查询,按2个变量排序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: realmex屏幕材质
- 下一篇: 如何安装无线网卡驱动(怎么重装无线网卡驱