MySQL如果数字选择其他列

时间:2017-02-17 08:18:32

标签: mysql regex

是否有mysql函数来检查值是否只是数字?

我不想要CONCAT 2列, 如果tbl3.column2是数字,那么与其他表列连接,如果是字符串,则其他列将使用相同的表。

SELECT tbl1.column1 as Column1, tbl2.column2 as Column2, 
IF tbl3.column2 REGEXP '^[0-9]+$' THEN CONCAT(tbl3.column1, ' ', tbl4.column1) ELSE CONCAT(tbl3.column1, ' ', tbl3.column2) END IF as Combined
FROM table1 tbl1
LEFT JOIN table2 tbl2 ON tbl1.id = tbl2.id
LEFT JOIN table3 tbl3 ON tbl3.id = tbl1.id
LEFT JOIN table4 tbl4 ON tbl4.id = tbl1.id
LEFT JOIN table5 tbl5 ON tbl5.id = tbl1.id 
WHERE
tbl5.column3 = ?
ORDER BY Column1 ASC

当前代码出错:

You have an error in your SQL syntax; check the manual that corresponds
 to your MySQL server version for the right syntax to use near 'tbl3.column2 REGEXP '^[0-9]+$'
    THEN CONCAT(tbl3.column1, ' ', tbl4.column1' at line

1 个答案:

答案 0 :(得分:2)

请试试这个:

SELECT tbl1.column1 AS Column1, tbl2.column2 AS Column2, 
IF(tbl3.column2 REGEXP '^[0-9]+$'
    , CONCAT(tbl3.column1, ' ', tbl4.column1)
    , CONCAT(tbl3.column1, ' ', tbl3.column2)
    ) AS Combined
FROM table1 tbl1
LEFT JOIN table2 tbl2 ON tbl1.id = tbl2.id
LEFT JOIN table3 tbl3 ON tbl3.id = tbl1.id
LEFT JOIN table4 tbl4 ON tbl4.id = tbl1.id
LEFT JOIN table5 tbl5 ON tbl5.id = tbl1.id 
WHERE
tbl5.column3 = ?
ORDER BY Column1 ASC