SQL - 选择多个NOT NULL且NOT EMPTY的列

时间:2016-01-25 22:35:54

标签: php mysql sql select

表' anbieter'看起来像:

Firma      | Blumenerde | Dachsubstrate | Rinden  | Substrate
-------------------------------------------------------------
Name 1     |             |       x       |         |
Name 2     |      x      |               |    x    |
Name 3     |      x      |       x       |    x    |
Name 4     |             |       x       |         |

我需要做的是:

输出名称(第一列)并选择所有列标题,这些标题是非空且非空('')

例如

Name 1 / Dachsubstrate
Name 2 / Blumenerde / Rinde
....

我尝试了以下内容:

SELECT * FROM anbieter WHERE Blumenerde IS NOT NULL AND TRIM(Blumenerde) <> ''

这对一栏很有用...... 但我需要让它与更多的列一起使用,如:

SELECT * FROM anbieter WHERE (Dachsubstrate OR Blumenerde) IS NOT NULL AND TRIM( ????? ) <> '';

如何&#34; TRIM()&#34;他们?

希望你理解我的观点......

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT Firma, 
        CONCAT_WS(' / ', 
            IF(TRIM(Blumenerde) != '', 'Blumenerde', NULL),
            IF(TRIM(Dachsubstrate) != '', 'Dachsubstrate', NULL),
            IF(TRIM(Rinden) != '', 'Rinden', NULL),
            IF(TRIM(Substrate) != '', 'Substrate', NULL)) AS cols
FROM anbieter
HAVING cols != ''

CONCAT_WS跳过NULL的参数。

DEMO

答案 1 :(得分:1)

这是你寻求的吗?

Select firma, concat(REPLACE(coalesce(Blumenerde,''),'x','Blumenerde'),REPLACE(coalesce(Dachsubstrate,''),'x','Dachsubstrate'),REPLACE(coalesce(Rinden,''),'x','Rinden'),REPLACE(coalesce(Substrate,''),'x','Substrate')
from anbieter 

答案 2 :(得分:0)

看起来你只需要用AND链接条件:

SELECT * FROM anbieter 
WHERE TRIM(Blumenerde) <> ''
AND TRIM(Dachsubstrate) <> ''
AND ...

另外,正如评论中所提到的,NOT NULL是一种盈余条件

答案 3 :(得分:0)

您想要检查是否有任何字段有值,换句话说,如果至少有一个字段不为空(这与查询所有字段都不为空的行有点不同)。所以你可以使用(基于你的例子):

SELECT * FROM anbieter 
WHERE 
NULLIF(Blumenerde, '') IS NOT NULL OR
NULLIF(Dachsubstrate, '') IS NOT NULL OR
NULLIF(Rinden, '') IS NOT NULL OR
NULLIF(Substrate, '') IS NOT NULL

或者您可以使用COALESCE检查至少有一个值不为空:

SELECT * FROM anbieter 
WHERE 
COALESCE(
    NULLIF(Blumenerde, ''),
    NULLIF(Dachsubstrate, ''),
    NULLIF(Rinden, ''),
    NULLIF(Substrate, '')
) IS NOT NULL