我有一个 mysql 表,其中有一些奇怪的 ID,如下所示:
╔═══╦════════════╦═════════════╦═══════════╦═════════════╦═══════════╗
║ ║ id ║ user_id ║ hours_a ║ hours_b ║ hours_c ║
╠═══╬════════════╬═════════════╬═══════════╬═════════════╬═══════════╣
║ 1 ║ 010120149 ║ 9 ║ 10 ║ 6 ║ 23 ║
║ 2 ║ 0212201310 ║ 10 ║ 2 ║ 8 ║ 10 ║
║ 3 ║ 021220138 ║ 8 ║ 1 ║ 4 ║ 9 ║
║ 4 ║ 020120149 ║ 9 ║ 3 ║ 8 ║ 10 ║
╚═══╩════════════╩═════════════╩═══════════╩═════════════╩═══════════╝
我正在尝试解析用户 ID 9 在 2014 年 1 月和 2014 年的总小时数。正如您从表中看到的那样,这是第一行和最后一行。
例如,01 01 2014 9
是第一行的ID,表示DD/MM/YYYY/ID。
我希望能够检索 user_id = 9 的所有时间(hours_a、hours_b 和 hours_c 分别,其中 day = 01 - 31>(循环遍历所有天数?)、月 = 01 和年 = 2014。
以这样的方式导出:
{"userid":"9","month":"01","year":"2014","total_hours_a":"13","total_hours_b":"14","total_hours_c":"33"}
ID 代表日、月、年和用户 ID:
目前在做什么
目前我正在选择所有表格:
$query="SELECT * FROM `weird_table` WHERE `id` LIKE 9";
将其打印为编码的 json:
$result = mysql_query($query);
$temp = 0;
$json = array();
while ($row = mysql_fetch_array($result))
{
$json[$temp]['id'] = $row['id'];
$json[$temp]['userid'] = $row['userid'];
$json[$temp]['hours_a'] = $row['hours_a'];
$json[$temp]['hours_b'] = $row['hours_b'];
$json[$temp]['hours_c'] = $row['hours_c'];
}
$temp++;
}
print json_encode($json);
mysql_close();
然后是客户端(因为我是一名前端开发人员),我将其混合、匹配和总结并获得我想要的结果。而不是做所有这些麻烦并给用户带来如此多的 CPU 痛苦;我希望服务器完成工作并打印出我正在寻找的内容。
最佳答案
试试这个:
SELECT *, (hours_a + hours_b + hours_c) totalHours
FROM weird_table
WHERE user_id = 9 AND
STR_TO_DATE(SUBSTRING(id, 1, 8), '%d%m%Y') BETWEEN '2014-01-01' AND '2014-01-31'
或
SELECT *, (hours_a + hours_b + hours_c) totalHours
FROM weird_table
WHERE user_id = 9 AND SUBSTRING(id, 3, 6) = '012014'
或
SELECT *, (hours_a + hours_b + hours_c) totalHours
FROM weird_table
WHERE user_id = 9 AND
YEAR(STR_TO_DATE(SUBSTRING(id, 1, 8), '%d%m%Y')) = 2014 AND
MONTH(STR_TO_DATE(SUBSTRING(id, 1, 8), '%d%m%Y')) = 1
关于mysql - PHP : Parse all data from mysql where the 3rd and 4th digit of the id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20904077/