SQL 中 where 子句内的 IF 语句
我正在开发一个日历应用程序。它以两种格式存储时间。该表具有以下列标题、开始日期、开始时间
。如果用户提供开始时间加上开始日期。数据库在startTime
列中存储UNIX时间戳(自UNIX epok以来的秒数),而startDate为NULL
。如果用户仅提供开始日期,数据库将以 nnnn-mm-dd
格式将日期存储在 startDate
中,将 NULL
存储在“startTime”中。我有这个数据库结构,因为它更容易显示世界各地的时间,因为不同的时区有不同的夏令时。
我想选择指定日期之后发生的事件。客户端计算机向服务器提供当天开始的 UNIX 时间戳 ($unix
) 和格式为 nnnn-mm 的日期 (
选择正确的日期。$date
) -dd
问题是,我不知道如何选择上面指定的那些日子。这个解决方案对我来说并不适用,尽管它有效:
SELECT *
FROM events
WHERE startDate >= '$date'
OR startTime >= '$unix'
问题是我在一些行中在 startTime
中提供了 unix 时间戳,我还在 startDate
中提供了日期code> 和其他我不想解释的原因。因此我无法使用上面的解决方案。
我需要某种在Where 子句中包含IF 语句的解决方案,例如:
SELECT *
FROM events
WHERE IF(startTime = NULL, startDate >= '$date', startTime >= '$unix')
我只是猜测这个解决方案。但这是对的吗?
I'm developing a calendar app. It stores times in two formats. The table have following columns title, startDate, startTime
. If the user provides start time plus start date. The database stores UNIX time stamp(number of seconds since UNIX epok) in the column startTime
, while startDate is NULL
. If the user only provide a start date, the database stores the date in format nnnn-mm-dd
in startDate
and NULL
in ´startTime`. I have this DB structure, because it's easier to display times around the world, because different timezones have different daylight saving times.
I want select the events that are occurring after a specified date. The client computer provide the server with a UNIX timestamp of the beginning of that day($unix
) and a date($date
) in the format nnnn-mm-dd
to select the correct dates.
The problem is, I don't know how to select those days that are occurring as specified above. This solution is not applicable for me, even though it works:
SELECT *
FROM events
WHERE startDate >= '$date'
OR startTime >= '$unix'
The thing is I have in some rows where unix time stamp is provided in startTime
, I also have a date provided in startDate
and other reason I which I don't want to explain. And because of that I can't use the solution above.
I need some kind of solution that have an IF statement inside the Where clause like:
SELECT *
FROM events
WHERE IF(startTime = NULL, startDate >= '$date', startTime >= '$unix')
I'm just guessing this solution. But is it right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
所有 SQL 方言都支持 CASE WHEN:
All SQL dialects support CASE WHEN:
您只需要在
WHERE
子句中添加一些组合的布尔逻辑:You just need some combined boolean logic in the
WHERE
clause:这不会返回任何 startDate 值为空的行
This will not return any row that has null value for startDate
我假设您想在 startDate 不为 null 时使用 startDate,并在 startTime 不为 null 时使用 startTime...然后尝试这个...
您也可以使用 CASE 语句,但这更有意义,更具可读性。
I'm assuming that you want to use startDate when startDate is not null, and startTime when startTime is not null... then try this...
You can use the CASE statement also, but this makes more sense is more readable.
我知道这是一个老问题,但我认为这是继续下去的最佳方法......
I know this is an old question but I think this is the best way to proceed...