我有这样的查询
"SELECT booking.referance_no AS ref_no,
booking.entry_date AS dep_date,
TIME_FORMAT(booking.entry_time,'%H:%i') as dep_time,
booking.first_name AS fname,
booking.last_name AS lname,
booking.mobile AS mobile
FROM booking WHERE $WHERE1
GROUP BY booking.book_id
UNION ALL
SELECT supplier.reference_no AS ref_no,
DATE_FORMAT(supplier.departure_date_time,'%d-%m-%Y') AS dep_date,
TIME_FORMAT(supplier.departure_date_time,'%H:%i') AS dep_time,
supplier.fname AS fname,
supplier.lname AS lname,
supplier_subscribers.mobile AS mobile
FROM supplier WHERE $WHERE2
ORDER BY `dep_date` ASC, `dep_time` ASC";
和Where子句
$WHERE1="STR_TO_DATE(booking.entry_date, '%d-%M-%Y') BETWEEN '".$from_date." 00:00:00' AND '".$to_date." 23:59:59'";
$WHERE2="supplier.departure_date_time BETWEEN '".$from_date." 00:00:00' AND '".$to_date." 23:59:59'";
情景一
在24小时内搜索ORDER BY dep_date ASC, dep_time ASC
我会得到这样的结果
在上面的快照中检查行63
和64
,结果按date
排序,但不是time
排序,第一个结果显示从supplier
表到行63
然后从表64
开始booking
,结果按照每个表(第一个supplier
表格然后booking
排序表),然后按date
和time
排序。
如果在24小时内仅使用ORDER BY dep_time ASC
进行搜索,我会按时间正确排序。
情景二
如果在48小时或更长时间内仅使用ORDER BY dep_time ASC
进行搜索,我会得到以下结果
未按日期排序当然它仅按time
排序,因此无用。
如果使用ORDER BY dep_date ASC, dep_time ASC
在48小时或更长时间内进行搜索,我会得到与第一个快照相同的结果;
supplier
然后booking
排序,但前24小时然后是24小时date
和time
排序。那么,无论日期范围是什么,我如何根据date
和time
对两个表的结果进行排序?
答案 0 :(得分:0)
使用Concat
ORDER BY concat(dep_date,' ',dep_time)` ASC
尝试以下查询,希望这可行
select * from (SELECT booking.referance_no AS ref_no,
booking.entry_date AS dep_date,
TIME_FORMAT(booking.entry_time,'%H:%i') as dep_time,
booking.first_name AS fname,
booking.last_name AS lname,
booking.mobile AS mobile
FROM booking WHERE $WHERE1
GROUP BY booking.book_id
UNION ALL
SELECT supplier.reference_no AS ref_no,
DATE_FORMAT(supplier.departure_date_time,'%d-%m-%Y') AS dep_date,
TIME_FORMAT(supplier.departure_date_time,'%H:%i') AS dep_time,
supplier.fname AS fname,
supplier.lname AS lname,
supplier_subscribers.mobile AS mobile
FROM supplier WHERE $WHERE2 ) as temp ORDER BY concat(dep_date,' ',dep_time)` ASC
答案 1 :(得分:0)
您可以 order by
supplier.departure_date_time
,因为这已经是正确的顺序。
好的,抱歉。我刚刚阅读了有关UNION
语法的MySQL Reference Manual。
要使用ORDER BY或LIMIT子句对整个UNION结果进行排序或限制,请为各个SELECT语句加上括号,并将ORDER BY或LIMIT置于最后一个之后。
"
(
SELECT
booking.referance_no AS ref_no,
booking.entry_date AS dep_date,
TIME_FORMAT(booking.entry_time,'%H:%i') as dep_time,
booking.first_name AS fname,
booking.last_name AS lname,
booking.mobile AS mobile
FROM booking
WHERE $WHERE1
GROUP BY booking.book_id
)
UNION ALL
(
SELECT
supplier.reference_no AS ref_no,
DATE_FORMAT(supplier.departure_date_time,'%d-%m-%Y') AS dep_date,
TIME_FORMAT(supplier.departure_date_time,'%H:%i') AS dep_time,
supplier.fname AS fname,
supplier.lname AS lname,
supplier_subscribers.mobile AS mobile
FROM supplier
WHERE $WHERE2
)
ORDER BY `dep_date` ASC, `dep_time` ASC
";