When working on a certain project, due to the need to search for the start time and end time, it was a long time to look up at that time, and special notes were recorded for future queries.
单表:
1.SELECT name,create_time FROM user_info WHERE create_time BETWEEN DATE('2019-12-12') AND DATE('2020-02-02');
2.SELECT name,create_time FROM user_info WHERE create_time >= DATE('2019-12-12') AND create_time <= DATE('2020-02-02');
多表联查:
SELECT
SUM(sell.`money`) AS sellMoney, DATE_FORMAT(sell.`create_time`,'%Y-%m-%d') AS sellStatsDate,
SUM(sell_reback.`money`) AS sellRebackMoney, DATE_FORMAT(sell_reback.`create_time`,'%Y-%m-%d') AS sellRebackStatsDate
FROM
sell
LEFT JOIN sell_reback
ON
DATE_FORMAT(sell.`create_time`,'%Y-%m-%d')=DATE_FORMAT(sell_reback.`create_time`,'%Y-%m-%d')
WHERE
and sell.`create_time` BETWEEN DATE(#{startTime}) AND DATE(#{endTime})
GROUP BY
DATE_FORMAT(sell.`create_time`,'%Y-%m-%d')
The above points to note:
DATE_FORMAT (specific time field, time style)
- The time field should be specific to which table time field
%Y-%m-%d
:The query time has year, month and day%Y-%m
: The query time is year and month%Y
: The query time is yearsAs
#{startTime}、#{endTime}
for the startTime and endTime types in
- String type
If you want to query is based on 年
, or in 年月
, then, or is 年月日
in the form of
SQL语句的写法:
SELECT
SUM(sell.`money`) AS sellMoney, DATE_FORMAT(sell.`create_time`,'${value}') AS sellStatsDate,
SUM(sell_reback.`money`) AS sellRebackMoney, DATE_FORMAT(sell_reback.`create_time`,'${value}') AS sellRebackStatsDate
FROM
sell LEFT JOIN sell_reback ON DATE_FORMAT(sell.`create_time`,'${value}')=DATE_FORMAT(sell_reback.`create_time`,'${value}')
GROUP BY
DATE_FORMAT(sell.`create_time`,'${value}')
value值的类型是字符串,注意此刻使用的是'${value}',如果使用的是#,则将单引号去掉
If the period of time you want to query is 年与年之间
, or 年月与年月
between, or 年月日与年月日
between
- For example, between 2017-2020
- For example, between 2019-03 and 2019-09
- For example, between 2020-01-10 —— 2020-04-20
SELECT
SUM(sell.`money`) AS sellMoney,
DATE_FORMAT(sell.`create_time`,#{value}) AS sellStatsDate
FROM
sell
WHERE
sell.`create_time` BETWEEN DATE(#{startTime}) AND DATE(#{endTime})
GROUP BY
DATE_FORMAT(sell.`create_time`,#{value})
Precautions:
- The values of startTime and endTime must be in the form of year-month-day . For example, if you want to query between 2020-01-10 —— 2020-04-20, then startTime=“2020-01-10”, endTime=“2020-04-20”, even if the query is 2019——2020 In between, it should also be in the form of year-month-day. Since the main search is for the year, the month and day can be arbitrary
- Since the return value of the query result is what we want, the affirmative result of the year query only wants the year, not the day and month, so the value value is needed at this time . The definition of the value value has been explained above, so only You need to pass in the corresponding value according to your needs