Concatenate date and varchar
题
I am need to select the date stored in a column transactionDate
datatype date
and time stored in column transactionTime
datatype varchar
from a table transactionTable
in mysql. My query is like
select concat( CAST( transactionDate as char), transactionTime) as transaction
from transactionTable
where id = 123
There are values in both the columns but the above returns me a null. How can I concat date
and varchar
columns?
解决方案
The CONCAT()
function returns NULL
when one of the arguments is null. You could use COALESCE()
to bypass the issue, converting the nulls to empty strings - or to any other constant value, for example '00:00:00'
for the time part:
select concat( coalesce(cast(transactionDate as char), ''),
' ',
coalesce(transactionTime, '00:00:00')
) as transaction
from transactionTable
where id = 123 ;
In fact, you don't really need an explicit cast()
, the cast to char
is implicit:
select concat( coalesce(transactionDate, ''),
' ',
coalesce(transactionTime, '00:00:00')
) as transaction
from transactionTable
where id = 123 ;
其他提示
You can also use CONCAT_WS
function which (i) converts datatype automatically (ii) skips NULL values*:
SELECT CONCAT_WS(' ', transactionDate, transactionTime) AS whatever
* If transactionDate
is NULL then the result won't contain leading space. If transactionTime
is NULL then result won't contain trailing space.