MySQL检索数据IF列不为空

时间:2013-02-08 19:47:43

标签: php mysql sql if-statement pdo

我有这张桌子:

title1  title2   type
---------------------
qwe1    xcv2     3
asd1    tzu      7
fgh1    (empty)  4

我有这个问题:

SELECT `title1` AS `title`, `type`
FROM `table`
UNION
SELECT `title2` AS `title`, `type`
FROM `table`
ORDER BY `title` ASC, type

(请参阅fiddle here)。

如果title2为空,如何转换此查询以使其不显示任何行?不应显示第1行。

我试图实现一个IF语句,但我总是遇到一个mysql错误。

4 个答案:

答案 0 :(得分:0)

这应该覆盖空字符串并且为null:

SELECT `title1` AS `title`, `type`
FROM `table`
UNION
SELECT `title2` AS `title`, `type`
FROM `table` where title2 is not null and title2 <> ''
ORDER BY `title` ASC, type

答案 1 :(得分:0)

您应该使用WHERE语句为查询定义条件

SELECT `title1` AS `title`, `type`
FROM `table`
WHERE `title1` IS NOT NULL AND LENGTH(`title1`) > 0
UNION
SELECT `title2` AS `title`, `type`
FROM `table`
WHERE `title2` IS NOT NULL AND LENGTH(`title2`) > 0
ORDER BY `title` ASC, type

答案 2 :(得分:0)

使用UNION时,删除重复项。您确定不想使用UNION ALL吗?另外,你有什么理由需要title2吗?它对我来说似乎没有正常化。

SELECT title1 AS title, `type`
FROM `table`
UNION ALL
SELECT title2 AS title, `type`
FROM `table`
WHERE title2 IS NOT NULL AND title2 <> ''

See the demo

答案 3 :(得分:0)

我认为,而不是检查title2 is not nulltitle2 <> '',最简单的方法是使用COALESCE将任何Null值转换为空,然后检查COALESCE的结果是否为&lt;&gt; ; '',像这样:

SELECT title1 AS title, `type`
FROM `table`
UNION
SELECT title2 AS title, `type`
FROM `table`
WHERE COALESCE(title2, '') <> ''

如果您不需要删除重复项,我认为最好使用UNION ALL而不是UNION。