我已经在这里阅读了一些类似的帖子,经过几个小时的绞尽脑汁,我仍然无法让它工作。
我在 MySQL 中有 2 个表: - 预订 - 预订状态历史记录
预订表的结构和数据:
id pt_id client_id timestamp notes
62 30 15 2015-02-02 07:00:00
booking_status_history表的结构和数据: (注意 booking_id 是上面预订表的外键)
id booking_id timestamp description details status
11 62 2015-02-02 00:40:42 Client made Booking (pending) test_detailsi pending
12 62 2015-02-02 00:40:45 PT confirmed booking (confirmed) test_details2 pending
18 62 2015-02-02 02:45:15 Client cancelled Booking (Medical Emergency) test_details3 pending
我想要实现的是从每个预订的状态列中获取最新值(此测试数据仅显示 1 个预订和 3 个历史值)。
目前我只实现了拉回所有历史结果,而不仅仅是拉回最新行。
我正在使用以下 PHP MySQLi 库:https://github.com/joshcam/PHP-MySQLi-Database-Class#join-method
这是我当前的代码,它似乎返回了所有历史记录。我尝试过使用 MAX 和 GROUPBY 的变体,因为我在旧线程中看到了其他人的工作,但由于某种原因,我无法将其应用于此场景。
$date = date('Y-m-d H:i:s', time());
$this->db->join("booking_status_history h", "b.id=h.booking_id", "LEFT");
$this->db->where('client_id', $id_param);
$this->db->where('b.timestamp', $date, ">");
$this->db->where('h.status', 'pending');
$this->db->orderBy("b.timestamp","desc");
$next_booking = $this->db->get("booking b", NULL, "b.*, h.status");
return $next_booking;
正如您从下面的输出中看到的,这将返回所有 3 个历史值:
Array (
[0] => Array (
[id] => 62
[pt_id] => 30
[client_id] => 15
[timestamp] => 2015-02-02 07:00:00
[notes] => [status] => pending
)
[1] => Array (
[id] => 62
[pt_id] => 30
[client_id] => 15
[timestamp] => 2015-02-02 07:00:00
[notes] => [status] => pending
)
[2] => Array (
[id] => 62
[pt_id] => 30
[client_id] => 15
[timestamp] => 2015-02-02 07:00:00
[notes] => [status] => pending
)
)
我很高兴不是每个人都会熟悉这个 PHP 库,所以即使有人可以通过原始 SQL 向我解释它,那就太棒了。
我尝试要做的是(用伪代码):
SELECT everything
FROM bothtables
WHERE booking.id=booking_status_history.booking_id
AND latest entry in booking_status_table
我希望这是有道理的。现在是凌晨 5 点,我整晚都在忙着处理一个巨大的代码块。
谢谢!
最佳答案
这似乎对我来说已经破解了!非常感谢 Jhecht 花时间帮助我:-)
SELECT b.*, h.booking_id, h.details, h.status FROM booking b JOIN booking_status_history h ON b.id = h.booking_id WHERE h.id = (SELECT MAX(id) FROM booking_status_history WHERE booking_id = b.id)
关于PHP 和 MySQL 在 MAX 列上执行联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28271453/