我遇到了一个有关日期时间选择器和MySQL的小问题。
我有一个PHP脚本,应该应在所选日期之前(包括该日期)获取记录。但是,数据集返回空。
这是脚本的SQL部分:
$sql = 'SELECT `pro_title`,
`pro_part_number`,
`name` AS flag_name,
`old_val`,
`new_val`
FROM `products`
INNER JOIN `flags` ON `id` = `pro_flag_id`
INNER JOIN `flag_history` ON `pro_part_number` = `part`
WHERE `pro_flag_id` IN(:flags)
AND STR_TO_DATE(`ts`, "%y-%m-%d") <= :dateTs;';
然后我使用PDO绑定参数:
array(
':flags' => implode(',', $flags), # this outputs 1,2,3
':dateTs' => $date # this outputs 2019-04-30
)
我还尝试将<=
更改为>=
无济于事(不是应该工作,但以为我会尝试)。
我遇到了很多SO帖子,但实际上没有什么让我到达那里。这是flag_history
表(存储ts
的表)的说明
MariaDB [mastern]> describe `flag_history`;
+---------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| part | varchar(25) | NO | | NULL | |
| ts | datetime | YES | | CURRENT_TIMESTAMP | |
| old_val | int(4) | YES | | NULL | |
| new_val | int(4) | YES | | NULL | |
+---------+-------------+------+-----+-------------------+----------------+
以及一些示例数据:
MariaDB [mastern]> select * from `flag_history` order by `id` desc limit 5;
+-------+----------+---------------------+---------+---------+
| id | part | ts | old_val | new_val |
+-------+----------+---------------------+---------+---------+
| 24026 | PART-001 | 2019-04-30 09:42:22 | 0 | 3 |
| 24025 | PART-002 | 2019-04-30 09:42:22 | 0 | 3 |
| 24024 | PART-003 | 2019-04-30 09:42:22 | 0 | 3 |
| 24023 | PART-004 | 2019-04-30 09:42:22 | 0 | 3 |
| 24022 | PART-005 | 2019-04-30 09:42:22 | 0 | 3 |
+-------+----------+---------------------+---------+---------+
然后,使用PART-001确保flag_id实际设置为:
MariaDB [mastern]> select `pro_flag_id` from `products` where `pro_part_number` = "PART-001";
+-------------+
| pro_flag_id |
+-------------+
| 3 |
+-------------+
因此,我不确定到底出了什么问题,对我来说逻辑和一切(MySQL newb)看起来应该可以工作,但它给了我空数据。我还尝试将INNER JOIN
更改为LEFT JOIN
,但是再次失败了。
我在做什么错了?
答案 0 :(得分:1)
我设法解决。当我真正在阅读flag_history
表时,我将主要的SELECT
焦点更改为flag_history
,并修改了SQL:
$sql = 'SELECT `old_val`, `new_val`, `ts`, `flags`.`name` AS flag_name, `pro_part_number`, `pro_title`
FROM `flag_history`
INNER JOIN `products` ON `pro_part_number` = `part`
INNER JOIN `flags` ON `pro_flag_id` = `flags`.`id`
WHERE `ts` <= :dateTs;';
我慢慢地添加了INNER JOIN
,并设法使它在使用flag_history
时起作用。我认为问题实际上可能归结于id
字段。字段不明确(flags
和flag_history
的{{1}}列)。奇怪的是,我没有得到这个错误(也许是因为我没有选择)。无论哪种方式,都可以通过更加具体地选择我的选择并从读取表而不是加入表来解决它。
请注意,从JOIN中删除id
段会显示约束错误。因此,我的猜测是,当我从另一张表中读取数据时,它没有第一次显示。