[英]If statement within mySql query
I've spent a lot of time searching for an answer to this problem online but I can't seem to come up with anything useful. 我已经花了很多时间在网上寻找这个问题的答案,但似乎无法提出任何有用的建议。
I'm pretty new to mySQL so I have a limited enough knowledge. 我对MySQL很陌生,所以我的知识有限。
I have a table events
with 6 columns: id
, event_name
, event_date
, event_close_time
, event_link
, and event_image
. 我有一个包含6列的表events
: id
, event_name
, event_date
, event_close_time
, event_link
和event_image
。
I'm trying to select everything from the database where the event_close_time is < current time if the event is on today and select all the other events in the future. 我正在尝试从数据库中选择event_close_time为<当前时间的所有内容(如果事件在今天进行),并在将来选择所有其他事件。
What I came up with is: 我想出的是:
SELECT * FROM `events`
WHERE `event_date` >= 'todays_date'
AND `event_close_time` > 'current_time'
ORDER BY `event_date`
but this doesn't do exactly what I want it to do. 但这并不能完全满足我的要求。 It returns all events that are on today or in the future as long as their closing time is earlier then the current time. 只要它们的关闭时间早于当前时间,它将返回当前或将来发生的所有事件。
It's important that I do it in 1 query because the ORDER BY clause at the end allows me to sort the events into the order I want to use in my web application. 在1个查询中执行此操作很重要,因为末尾的ORDER BY子句允许我将事件排序为要在Web应用程序中使用的顺序。
Could anyone point out the adjustments I need to make to get the desired result? 谁能指出我需要进行调整才能获得所需的结果?
You should do this with one select
and the correct where
clause: 您应该使用一个select
和正确的where
子句来做到这一点:
SELECT *
FROM `events`
WHERE (event_date = CURDATE() AND event_close_time < CURTIME()) or
(event_date > CURDATE())
ORDER BY `event_date`;
Implementing or
logic by using union
or union all
is a bad habit to get into. 通过使用union
或union all
来实施or
逻辑是一个坏习惯。 For one thing, it requires scanning the events
table twice, once for each condition. 一方面,它需要扫描events
表两次,每种情况一次。 The single where
only scans the table once. 单where
仅扫描一次表。
How about this? 这个怎么样?
SELECT *
FROM events
WHERE event_date = CURDATE()
AND event_close_time < CURTIME()
UNION ALL
SELECT *
FROM events
WHERE event_date > CURDATE()
ORDER BY event_date
This could also be accomplished with an OR
instead of the UNION ALL
, but I have found that UNIONS tend to be more efficient because ORs cause indexes not to be used (at least in MySQL). 这也可以用OR
而不是UNION ALL
来完成,但是我发现UNIONS往往更有效,因为OR导致不使用索引(至少在MySQL中如此)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.