mysql - PHP : Parse all data from mysql where the 3rd and 4th digit of the id

标签 mysql sql datetime select substring

我有一个 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: enter image description here


目前在做什么

目前我正在选择所有表格:

$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/

相关文章:

php - 显示来自同一 mysql 列的两个单独值的问题

mysql - 如何在linux操作系统下升级xampp中的mysql(innodb)版本

PHP日期偏移量

php - 检测 DateTime 对象中是否指定了时间

c# - 如何在 .NET 中获取此 DateTime 格式

java - 当我尝试连接到 Mysql 时检测到 JSONException 时,如何修复错误?

php - Yii 中的日期选择器将数据存储为 yy MM d 格式

mysql - 将列添加到现有的唯一键?

sql - TSQL 选择一个我也在计算的字段

mysql - 如果表不存在,如何创建*和填充*表?