我不知道如何查询我的数据库,以便它返回一个动态生成来自给定查询的列的结果集。下面是我要查询的表格
+---------+------------+-------+
| user_id | date | unit |
+---------+------------+-------+
| 1 | 2014-11-08 | 2 |
| 1 | 2014-11-08 | 5 |
| 1 | 2014-11-07 | 1 |
| 2 | 2014-11-07 | 2 |
| 1 | 2014-11-08 | 1 |
| 1 | 2014-11-07 | 2 |
+---------+----------=-+-------+
我希望能够选择特定用户输入的所有单位,当日期介于2个日期之间且单位数介于2个值之间时。简单地说,查询将是:
SELECT `unit`
FROM `unit_table`
WHERE user_id = 1
AND (`date` BETWEEN '2014-11-05' AND '2014-11-08')
AND (`unit` BETWEEN 1 AND 5)
但是我希望结果集的格式如下,其中TRUE和FALSE分别为1和0
+------+------------+------------+------------+------------+
| unit | 2014-11-05 | 2014-11-06 | 2014-11-07 | 2014-11-08 |
+------+------------+------------+------------+------------+
| 1 | FALSE | FALSE | TRUE | TRUE |
| 2 | FALSE | FALSE | TRUE | TRUE |
| 3 | FALSE | FALSE | FALSE | FALSE |
| 4 | FALSE | FALSE | FALSE | FALSE |
| 5 | FALSE | FALSE | FALSE | TRUE |
+------+------------+------------+------------+------------+
这是否可能,或者是否需要在结果集中以编程方式完成?
如果无法就如何设置数据库提出任何建议,我们将不胜感激。注意:我希望避免将特定日期用作列,因为该表每天都会添加大量数据。
答案 0 :(得分:0)
感谢Rahul让我走上正轨!我最终实现了以下查询,它给了我想要的东西。如果其他人有更好的答案,请随时回答。
SELECT unit_number AS unit,
SUM(IF(date=?,1,0)) AS day4,
SUM(IF(date=?,1,0)) AS day3,
SUM(IF(date=?,1,0)) AS day2,
SUM(IF(date=?,1,0)) AS day1,
SUM(IF(date=?,1,0)) AS day0
FROM `table_name`
WHERE user_id = 1 AND (unit BETWEEN 1 AND 5)
GROUP BY unit