php mysql asc/desc 顺序
表:
**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
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 RESULT:
DATE TIMES
2010-02-22 10:30
2010-02-25 09:30
2010-02-27 11:00
anyone notice that on the table result. the times is incorrect order?
i changed another way round with ASC / DESC, and still the times showing the last id_timeslot?
EXPECTED RESULT:
DATE TIMES
2010-02-22 09:30
2010-02-25 09:30
2010-02-27 10:00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
GROUP BY bookslot.b_ref
正在对记录进行分组,因此您只能看到每种情况下的最后一次。尝试使用
Your
GROUP BY bookslot.b_ref
is grouping the records, so you're only seeing the last time in each case.Try using
虽然你的 SQL 在语法上是正确的,但它会产生意想不到的结果。
通常,您
SELECT
的列必须在GROUP BY
子句中指定,或者应包含在聚合函数内。否则,MySQL 将自行决定在 GROUP BY 操作中消除哪些记录。 ORDER BY 并不重要,因为它是在 GROUP BY 操作之后应用的。您应该更好地修改您的查询,如下所示:While your SQL is syntactically correct but it will produce unexpected results.
Normally, the columns that you
SELECT
must be specified in theGROUP BY
clause or should be enclosed inside an aggregate function. Otherwise, MySQL will determine, at its own discretion, which records to eliminate in theGROUP BY
operation. TheORDER BY
does not matter because it is applied after theGROUP BY
operation. You should better revise your query like this:由于目标似乎是收集每个书位的最早时间段,因此需要使用
MIN
缩小结果范围Since the goal appears to be about collecting the earliest timeslots for each bookslot then it's required to narrow the results with
MIN