SQL - 仅显示周末或工作日价格,具体取决于日期

时间:2016-05-03 13:38:42

标签: mysql sql

我有一条SQL语句从数据库返回有关可用日期的信息。

SELECT * 
FROM   venue 
WHERE  NAME NOT IN (SELECT NAME 
                    FROM   venue_booking 
                    WHERE  date_booked = '2016-01-17') 
       AND capacity > 150 

该表有两列,工作日价格和周末价格。 我只需要在最终输出中显示其中一个,具体取决于日期。 例如。如果日期是在一周内,则显示该场地的工作日价格。

4 个答案:

答案 0 :(得分:1)

来自MySQL参考here

  

DAYOFWEEK(日期)

     

返回日期的工作日索引(1 =星期日,2 =星期一,...,7 =   星期六)。这些索引值对应于ODBC标准。

您可以将此功能与IFCASE一起使用来解决您的问题。

SELECT `all_fields_other_than_price`, 
  CASE WHEN DAYOFWEEK('2016-01-17') IN (1,7) THEN v.weekend_price
  ELSE v.weekday_price
  END AS `VENUE_PRICE`
FROM venue v
WHERE name NOT IN(
  SELECT name FROM venue_booking WHERE date_booked = '2016-01-17') 
AND capacity > 150;

答案 1 :(得分:0)

你的意思是这样吗?

SELECT *, IF(dayofweek(NOW()) = 7, v.weekday_price, v.weekend_price) as final_price FROM venue v
WHERE name NOT IN(SELECT name FROM venue_booking WHERE date_booked = '2016-01-17') 
AND capacity > 150

注意

7中的号码IF(dayofweek(NOW()) = 7更改为您想要的日期号码。

答案 2 :(得分:0)

使用此查询:

    Select CASE when DAYOFWEEK(booked_date)>1 and
    DAYOFWEEK(booked_date)< 7 then weekday_price
    ELSE weekend_price 
    END  as price
    From venue
WHERE NAME NOT IN (SELECT NAME FROM venue_booking WHERE date_booked = '2016-01-17') AND capacity > 150 

答案 3 :(得分:0)

在查询中多次重复同一日期可能很危险(在保持查询一致方面)。此外,我不是NOT IN的粉丝,因为它不会直观地使用NULL值。

所以,您可以考虑:

SELECT v.*,
       (CASE WHEN dayofweek(thedate) IN (1, 7) then weekend_price
             ELSE weekday_price
        END) as price
FROM (SELECT date('2016-01-17') as thedate) params CROSS JOIN
     venue v LEFT JOIN
     venue_booking vb
     ON v.name = vb.name AND vb.date_booked = thedate
WHERE vb.name IS NULL AND
      v.capacity > 150