-1

我有这张桌子:

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

(请在此处查看小提琴)。

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

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

4

4 回答 4

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 <> ''

查看演示

于 2013-02-08T19:57:50.643 回答
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
于 2013-02-08T19:55:27.300 回答
0

我认为,而不是检查 iftitle2 is not nulltitle2 <> '',最短的方法是使用 COALESCE 将任何 Null 值转换为空,然后检查 COALESCE 的结果是否为 <> '',如下所示:

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

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

于 2013-02-08T20:16:16.217 回答
0

这应该涵盖空字符串和空值:

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
于 2013-02-08T19:53:32.597 回答