多SQL选择语句

时间:2019-02-09 10:55:36

标签: mysql sql wampserver

我有一个这样的表:

| name    |  salary |  day  |  month   |
| james   |  200.00 |    2  | january  |
| marie   |  400.00 |    4  | january  |
| jimmy   |  300.00 |    7  | january  |
| Fredd   |  700.00 |    3  | february |
| rosieli |  500.00 |    5  | february |
| rosela  |  800.00 |    6  | february |

如果表名是'db_table',我该如何编写sql select查询来选择1月4日至2月5日的记录。
像这样:

select * from db_table between day='4',month='january' and day='5' and month='february'";

请我如何编写适当的sql语句以获得所需的结果。以使表如下所示:

| name    |  salary |  day  |  month   | 
| marie   |  400.00 |    4  | january  |
| jimmy   |  300.00 |    7  | january  |
| Fredd   |  700.00 |    3  | february |
| rosieli |  500.00 |    5  | february |

谢谢

4 个答案:

答案 0 :(得分:1)

您需要将日期设为数字,但这就是它:

SELECT *
FROM db_table
WHERE (day >= 4 and month = 'January')
   OR (day <= 5 and month = 'February')

例如一月至四月:

SELECT *
FROM db_table
WHERE (day >= 4 and month = 'January')
   OR (day <= 5 and month = 'April')
   OR month IN ('February','March')

答案 1 :(得分:0)

您必须在month语句中使用daybetween创建一个可比较的字符串:

select * from db_table where 
concat(case month 
         when 'january' then '01'
         when 'february' then '02'
         ........................
         when 'december' then '12'
       end, case when day < 10 then '0' else '' end, day) between '0104' and '0205'

像这样,您可以通过仅修改开始日期和结束日期来比较任何日期范围。

答案 2 :(得分:0)

  

我该如何编写sql select查询来选择1月4日至2月5日的记录。

select  *
from    db_table
where   (month = 'january' and 4 <= cast(day as int)) or
        (month = 'february' and cast(day as int) <= 5)

请注意,具有单独的月份和日期列的表设计使查询变得困难。在年份的界限上将变得更加困难。更好的设计将利用数据库的本机datetime列类型。然后您可以像这样查询:

select  *
from    db_table
where   dt_col between '2019-01-04' and '2019-02-05'

答案 3 :(得分:0)

您确实应该使用日期。

select t.*
from t
where str_to_date(concat_ws(2020, month, day), '%Y %M %d') between '2020-01-04' and '2020-02-05';

在可能的情况下,应该使用日期进行日期比较。

我使用2020是因为它是a年,所以它将处理2月29日。

解决此问题后,应修复数据模型以包含实际日期,而不是月/日组合。