我正在为一个客户端开发一个小项目,数据库中的数据让我有点麻烦。我正在从数据库中填写付费分期付款的搜索表单。我可以把数据弄好,它的日期字段让我烦恼。
每个分期的日期,月份和年份都有单独的字段。有没有办法可以在合并的字段中使用CONCAT
或DATE
或甚至使用CAST
来搜索数据。
我试过以下
SELECT DATE_FORMAT( CONCAT( received_date, received_month, received_year ) , '%d/%m/%Y' ) FROM policy_installments
和
SELECT DATE_FORMAT(STR_TO_DATE(CONCAT('pit.received_date', '-', 'pit.received_month','-', 'pit.received_year'), '%d-%m-%Y') AS mydate, '%d-%m-%Y') AS modate FROM policy_installments pit ORDER BY mydate
和
SELECT * FROM policy_installments WHERE CONCAT(CAST(received_date AS CHAR),"-",CAST(received_month AS CHAR),"-",CAST(received_year AS CHAR)) >= '1-1-2014' AND CONCAT(CAST(received_date AS CHAR),"-",CAST(received_month AS CHAR),"-",CAST(received_year AS CHAR)) <= '31-3-2014'
当我使用以下内容时,我会得到一些意想不到的数据:
SELECT CONCAT_WS( received_date, "-", received_month, "-", received_year ) FROM policy_installments
RESULT
2d313130312d3132303039
2d3237313032372d323732303039 etc etc
3个字段中的每一个都是INT(11)
类型。
然而,这些都没有给我正确的数据。有没有办法我可以转换所有3个字段并使用日期传递到查询,以使我能够正确地获取正确的数据?
非常感谢任何帮助!
答案 0 :(得分:5)
要将连接字符串转换为日期,字符串的格式应与您用于转换的格式相同。
对于dd/mm/yyyy
格式的日期字符串,应使用%d/%m%Y
格式转换为sql日期。
示例:
SELECT STR_TO_DATE(
CONCAT( received_date, '/', received_month, '/', received_year ),
'%d/%m/%Y'
) as rcvd_date
FROM policy_installments
要与其他日期进行比较,您可以使用BETWEEN
子句。
示例:
SELECT * FROM policy_installments
WHERE
STR_TO_DATE(
CONCAT( received_date, '-', received_month, '-', received_year ),
'%d-%m-%Y'
) BETWEEN STR_TO_DATE( '1-1-2014', '%d-%m-%Y' )
AND STR_TO_DATE( '31-3-2014', '%d-%m-%Y' )
请参阅:
MySQL: STR_TO_DATE(str,format):将字符串转换为日期
答案 1 :(得分:0)
通常,您希望避免在列上执行该功能。而是在文字上执行该功能,以便您可以利用列上的索引:
SELECT *
FROM policy_installments
WHERE received_year = YEAR('2014-03-31')
AND received_month = MONTH('2014-03-31')
AND received_date = DAY('2014-03-31')
在received_year,received_month和received_date上添加多列索引,你会做得很好。
显然,此方法仅适用于=
比较。对于<=
,它变得有点复杂:
SELECT *
FROM policy_installments
WHERE
received_year < YEAR('2014-03-31')
UNION
SELECT *
FROM policy_installments
WHERE
received_year = YEAR('2014-03-31')
AND received_month < MONTH('2014-03-31')
UNION
SELECT *
FROM policy_installments
WHERE
received_year = YEAR('2014-03-31')
AND received_month = MONTH('2014-03-31')
AND received_date <= DAY('2014-03-31')
但是这个较长的查询仍然可以使用索引。
为简化起见,请考虑创建一个实际的日期列,并使用适当的值更新它。