我有这种表:
| 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语句,以获得所需results.so该表如下所示:
| name | salary | day | month |
| marie | 400.00 | 4 | january |
| jimmy | 300.00 | 7 | january |
| Fredd | 700.00 | 3 | february |
| rosieli | 500.00 | 5 | february |
谢谢
你真的应该做到这一点使用日期。
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
,因为它是一个闰年,因此它会处理2月29日。
一旦你已经解决了这一点,你应该可以解决你的数据模型包含的实际日期,而不是月/日的组合。
你需要做一天的工作,但是这是它:
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')
我如何写一个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'
你必须创建一个可比的串出month
和day
在between
语句中使用:
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'
这样你可以通过修改只有起始日期和结束日期比较任意日期范围。