1

我有以下 MySQL SELECT 语句(连同 PHP):

SELECT *
FROM EVENTS
WHERE (
 time1
 BETWEEN "2013-04-22 19:30:00"
 AND "2013-04-22 19:50:00"
)
OR (
 time2
   BETWEEN "2013-04-22 19:30:00"
   AND "2013-04-22 19:50:00"
)

上面的查询返回以下行:

    id   |        time1        |       time2        |
   -------------------------------------------------
    26     2013-04-22 19:45:00  2013-04-26 12:25:00

所以,很明显,time1是什么返回了行。

我的问题是:当我使用上面的 SELECT 语句遍历行时,如何确定是 time1 还是 time2 '触发'(因为没有更好的术语)要返回的行?

任何帮助都会很棒!

4

3 回答 3

6
SELECT  *,
        IF(time1 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00", 
          'Time1', 'Time2')  Result
FROM    EVENTS
WHERE   time1 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00" OR
        time2 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00"

名为的附加列Result仅测试条件返回 true 的列。例如,如果两者都返回 true,则只会time1出现在result列上。

更新 1

SELECT  *,
        CASE
            WHEN time1 BETWEEN '2013-04-22 19:30:00' AND '2013-04-22 19:50:00' AND 
                 time2 BETWEEN '2013-04-22 19:30:00' AND '2013-04-22 19:50:00'
            THEN 'Time1 and Time2'
            WHEN time1 BETWEEN '2013-04-22 19:30:00' AND '2013-04-22 19:50:00' 
            THEN 'Time1'
            ELSE 'Time2'
        END Result
FROM    EVENTS
WHERE   time1 BETWEEN '2013-04-22 19:30:00' AND '2013-04-22 19:50:00' OR
        time2 BETWEEN '2013-04-22 19:30:00' AND '2013-04-22 19:50:00'
于 2013-04-23T03:34:54.267 回答
1

JW 的答案是正确的,但是我会为两个“触发器”创建一个标志(因为它们都可以触发):

SELECT
    *,
    IF(time1 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00"), 'yes', 'no') AS in_time1,
    IF(time2 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00"), 'yes', 'no') AS in_time2
FROM EVENTS
WHERE
    time1 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00"
    OR time2 BETWEEN "2013-04-22 19:30:00" AND "2013-04-22 19:50:00"
于 2013-04-23T03:40:22.290 回答
0

我没有测试过,但是像这样:

SELECT *,  IF(time1
 BETWEEN "2013-04-22 19:30:00"
 AND "2013-04-22 19:50:00",1,0) as fromtime1
FROM EVENTS
WHERE (
 time1
 BETWEEN "2013-04-22 19:30:00"
 AND "2013-04-22 19:50:00"
)
OR (
 time2
   BETWEEN "2013-04-22 19:30:00"
   AND "2013-04-22 19:50:00"
)

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

于 2013-04-23T03:37:28.340 回答