没有WHERE的INT比较

时间:2014-01-23 12:50:21

标签: mysql sql

2 个答案:

答案 0 :(得分:2)

轻微一点,您的查询中至少有三个语法错误。在第0天之后有逗号,在datediff()中缺少日期部分,以及双等号。至于你想要完成什么,它可能是一种案例结构。

select case 
when datediff(day, date1, date2) = 0 then 'Day 0'
when abs(datediff(day, date1, date2)) = 1 then 'Day 1'
else 'something else' end WhatDay
from etc

你可能想要一个where子句,这样你就不会查询整个表。这样做很少是必要的。

答案 1 :(得分:0)

如果你需要多个列,那么你只有一个现实的选择,一个CASE语句,但这很麻烦。然而,通过一点点加入我们可以使它更清洁。我们假设表的关键是Id,我们可以写一个这样的语句:

SELECT t.*,
    CASE WHEN i.diff = 0 THEN 'Day 0' ELSE NULL END AS Day0,
    CASE WHEN i.diff = 1 THEN 'Day 1' ELSE NULL END AS Day1,
    CASE WHEN i.diff = 2 THEN 'Day 2' ELSE NULL END AS Day2,
    CASE WHEN i.diff = 3 THEN 'Day 3' ELSE NULL END AS Day3,
    CASE WHEN i.diff = 4 THEN 'Day 4' ELSE NULL END AS Day4,
    CASE WHEN i.diff = 5 THEN 'Day 5' ELSE NULL END AS Day5,
FROM table t
    JOIN (
        SELECT Id, DATEDIFF(
            STR_TO_DATE(date, '%Y-%m-%d %H:%i:%s'), b.datetwo
        ) AS diff
        FROM table
    ) i ON i.Id = t.Id AND i.diff >= 0 AND i.diff <= 5

通过这个声明,我们现在知道每行有多少桶;如果值不是NULL