TABLE:
**timeslot**:
----------
id_timeslot times
1 09:00
2 09:30
3 10:00
4 10:30
5 11:00
**bookslot**
id id_timeslot date b_ref
-------------------------------------------
1 2 2010-02-22 001
2 3 2010-02-22 001
3 4 2010-02-22 001
4 5 2010-02-22 001
5 2 2010-02-25 002
6 3 2010-02-27 003
7 4 2010-02-27 003
8 5 2010-02-27 003
PHP
$q = $mysqli->query("SELECT * FROM bookslot
LEFT JOIN timeslot ON bookslot.id_timeslot = timeslot.id_timeslot
WHERE bookslot.status = 1
GROUP BY bookslot.b_ref
ORDER BY bookslot.date ASC, bookslot.id_timeslot ASC LIMIT 20");
HTML结果:
DATE TIMES
2010-02-22 10:30
2010-02-25 09:30
2010-02-27 11:00
任何人都会注意到桌面上的结果。时间是不正确的顺序?
我用ASC / DESC改变了另一种方式,但仍显示最后一次id_timeslot?
预期结果:
DATE TIMES
2010-02-22 09:30
2010-02-25 09:30
2010-02-27 10:00
答案 0 :(得分:3)
您的GROUP BY bookslot.b_ref
正在对记录进行分组,因此您只会在每种情况下看到最后一次。
尝试使用
SELECT date, time, MIN(bookslot.id_timeslot)
FROM bookslot
LEFT JOIN timeslot ON bookslot.id_timeslot = timeslot.id_timeslot
WHERE bookslot.status = 1
GROUP BY bookslot.b_ref
ORDER BY bookslot.date ASC, bookslot.id_timeslot ASC LIMIT 20
答案 1 :(得分:1)
虽然你的SQL在语法上是正确的,但它会产生意想不到的结果。
通常,必须在SELECT
子句中指定GROUP BY
的列,或者将其括在聚合函数中。否则,MySQL将自行决定在GROUP BY
操作中消除哪些记录。 ORDER BY
并不重要,因为它是在GROUP BY
操作之后应用的。您应该更好地修改您的查询:
SELECT b_ref, MIN(ADDTIME(date, times)) AS complete_datetime
FROM bookslot
LEFT JOIN timeslot ON bookslot.id_timeslot = timeslot.id_timeslot
WHERE bookslot.status = 1
GROUP BY bookslot.b_ref
ORDER BY bookslot.date, bookslot.id_timeslot
答案 2 :(得分:1)
由于目标似乎是收集每个图书位置的最早时段,因此需要使用MIN
缩小结果
SELECT b.id, b.id_timeslot, b.date, MIN(`date`) , t.times
FROM bookslot b
LEFT JOIN timeslot t ON b.id_timeslot = t.id_timeslot
GROUP BY b.b_ref