我有一份日期清单:
1/1/2011
2/2/2011
3/3/2011
4/4/2011
5/5/2011
我需要取出“x”个日期并将其标记为已启用。
=>得到2个最老的,然后我需要
1/1/2011 - 0 (enabled)
2/2/2011 - 0
3/3/2011 - 1 (disabled)
4/4/2011 - 1
5/5/2011 - 1
=>得到3个最老的,然后我需要
1/1/2011 - 0 (enabled)
2/2/2011 - 0
3/3/2011 - 0
4/4/2011 - 1 (disabled)
5/5/2011 - 1
我可以这样:
select * from table order by date_column limit 2; - for 2 entries.
select * from table order by date_column limit 3; - for 3 entries.
但是如何在单个查询中根据日期值添加1或0?有什么办法可以在一个查询中完成吗?
答案 0 :(得分:1)
此查询的工作原理是假设日期是唯一的:
SELECT
A.date_column,ISNULL(B.date_column) enabled
FROM
`table` LEFT JOIN
(SELECT date_column FROM `table` ORDER BY date_column LIMIT 3) B
USING (date_column);
如果表格中的日期不唯一,请尝试以下查询:
SELECT
A.date_column,
IF(ISNULL(B.date_column)=0,'0 (enabled)','1 (disabled)') status
FROM
`table` A LEFT JOIN
(
SELECT date_column
FROM (SELECT DISTINCT date_column FROM `table` ORDER BY date_column) AA
LIMIT 3
) B
USING (date_column);
试一试!!!
这次我尝试了你的数据:
use junk
drop table `table`;
create table `table` (date_column DATE);
INSERT INTO `table` VALUES
('2011-01-01'),
('2011-02-02'),
('2011-03-03'),
('2011-04-04'),
('2011-05-05');
SELECT * FROM `table`;
SELECT
A.date_column,
IF(ISNULL(B.date_column)=0,'0 (enabled)','1 (disabled)') status
FROM
`table` A LEFT JOIN
(SELECT date_column FROM
(SELECT DISTINCT date_column FROM `table` ORDER BY date_column) AA
LIMIT 3) B
USING (date_column);
这是输出:
mysql> use junk
Database changed
mysql> drop table `table`;
Query OK, 0 rows affected (0.02 sec)
mysql> create table `table` (date_column DATE);
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO `table` VALUES
-> ('2011-01-01'),('2011-02-02'),('2011-03-03'),
-> ('2011-04-04'),('2011-05-05');
Query OK, 5 rows affected (0.05 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM `table`;
+-------------+
| date_column |
+-------------+
| 2011-01-01 |
| 2011-02-02 |
| 2011-03-03 |
| 2011-04-04 |
| 2011-05-05 |
+-------------+
5 rows in set (0.00 sec)
mysql> SELECT
->
-> A.date_column,
-> IF(ISNULL(B.date_column)=0,'0 (enabled)','1 (disabled)') status
-> FROM
-> `table` A LEFT JOIN
-> (SELECT date_column FROM
-> (SELECT DISTINCT date_column FROM `table` ORDER BY date_column) AA
LIMIT 3) B
-> LIMIT 3) B
-> USING (date_column);
+-------------+--------------+
| date_column | status |
+-------------+--------------+
| 2011-01-01 | 0 (enabled) |
| 2011-02-02 | 0 (enabled) |
| 2011-03-03 | 0 (enabled) |
| 2011-04-04 | 1 (disabled) |
| 2011-05-05 | 1 (disabled) |
+-------------+--------------+
5 rows in set (0.00 sec)
答案 1 :(得分:1)
select
T1.DateColumn,
Case when Isnull(T2.DateColumn)
then 1
Else 0 end
as disabled
from table T1 left outer join
(select dateColumn from table
order by date_column asc limit 3) T2
On t1.dateColumn =t2.DateColumn
Order by t1.datecolumn asc