【问题标题】:php mysql asc/desc orderphp mysql asc/desc 命令
【发布时间】:2011-07-01 23:49:11
【问题描述】:

表格:

**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

【问题讨论】:

  • 在我看来是正确的,2010-02-22 10:30 出现在 2010-02-25 09:302010-02-27 11:00 之前。
  • 好吧,我找不到你想要达到的目标。但是2010-02-27 不能与10:00 关联,因为它的timeid 是5,即11:00 ...
  • 虽然您在 WHERE 子句中使用它,但您的示例也缺少 booklot 表中的状态列。这可能与它有关吗?

标签: php mysql sql date group-by


【解决方案1】:

您的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

【讨论】:

    【解决方案2】:

    由于目标似乎是收集每个书位的最早时间段,因此需要使用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
    

    【讨论】:

      【解决方案3】:

      虽然您的 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-27
        • 2021-04-29
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        • 1970-01-01
        相关资源
        最近更新 更多