我有一个
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(循环所有日期?),month = 01和year = 2014.
要以这样的方式导出:
{"userid":"9","month":"01","year":"2014","total_hours_a":"13","total_hours_b":"14","total_hours_c":"33"}
ID代表Day,Month,Year和Userid,如下所示:
目前我在做什么
目前我正在选择所有表格:
$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痛苦;我希望服务器完成工作并打印我正在寻找的东西.
试试这个:
原文链接:https://www.f2er.com/php/137120.htmlSELECT *,(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,'%d%m%Y')) = 2014 AND MONTH(STR_TO_DATE(SUBSTRING(id,'%d%m%Y')) = 1