【问题标题】:sqlite if no rows returned print 0sqlite 如果没有返回行打印 0
【发布时间】:2012-07-17 04:04:53
【问题描述】:

我有以下疑问:

 SELECT user_tag, device_type,  ip_address

 FROM
 devices 

 WHERE (user_tag like '|%frt%|'
 OR user_tag like '|%bck%|'
 OR user_tag like '|%ppp%|'
 OR user_tag like '|%smes%|'
 OR user_tag like '|%gm%|')

现在,如果只为 user_tag 'frt' 返回记录,我只会收到一行(如您所料)。有没有办法为空白行设置默认值,例如,对于不返回任何实际数据的行,我会收到“0”或类似的值?

【问题讨论】:

    标签: sqlite


    【解决方案1】:

    此查询是“草稿”。由于我使用所有类型的 SQL,有时我会遇到特定于 SQLite 的语法问题,而且我现在没有任何方法来测试这个查询,所以它可能需要一些语法修改。

    但它的想法是交叉的...... 使用您的硬编码值列表,使其成为子查询并对其进行左连接而不是 where。

    当给定类型没有任何用户标签时,user_tag_exists 应该为 0。

    Select CASE WHEN d.user_tag is null THEN '0' ELSE '1' END AS user_tag_exists,
           tagTypes.tagType,
           d.user_tag, d.device_type, d.ip_address
    From
    (
        Select '%frt%' as tagType
        UNION
        Select '%bck%' as tagType
        UNION
        Select '%ppp%' as tagType
        UNION
        Select '%smes%' as tagType
        UNION
        Select '%gm%' as tagType
    ) as tagTypes
    left join
        devices d
            on d.device_type like tagTypes.tagType
    

    【讨论】:

    • 谢谢。我在这里做了一个 SQL Fiddle:sqlfiddle.com/#!3/c6b52/1,它似乎没有正确运行。有什么想法吗?
    • 嘿,Ben,这是一个非常简洁的工具!我将来肯定会使用它。我正在通过更改更新答案。您设置数据的方式,您为 device_type 提供 ppp..bck .. 等。但在您的示例中,您在 user_tag 上的位置。
    • 啊,我现在明白了。 user_tag 是正确的选择,我只是把它们弄混了
    【解决方案2】:

    我不确定你是否想要:

    1. 列中的值为“0”而不是 null
    2. 如果是 '0' 的行 不存在类似于值的 user_tag。

    如果您正在寻找 1),您可以使用 CASE 语句。

     SELECT 
            user_tag, 
            CASE WHEN device_type is not null THEN device_type ELSE '0' END as device_type, 
            ip_address
    
     FROM
     devices 
    
     WHERE (user_tag like '|%frt%|'
     OR user_tag like '|%bck%|'
     OR user_tag like '|%ppp%|'
     OR user_tag like '|%smes%|'
     OR user_tag like '|%gm%|')
    

    即使 device_type 为空,这也会为您提供一个 device_type '0'。

    【讨论】:

    • 谢谢。我在“,”附近收到此错误错误 [HY000]:语法错误(1)
    • 抱歉,我现在没有办法检查我的 SQLite 语法。我编辑了查询,忘记添加 end 语句。我还添加了一个 as 语句。
    • 再看这个,我实际上是在寻找选项#2'如果不存在类似于值的 user_tag,则为'0'的行。"
    • 对不起,给定的查询仅针对具有空值的列,而不是缺少的语句。虽然你可以编写一个查询来做你想做的事,但在代码中而不是 SQLite 中处理它可能更容易。我能想到的唯一方法是非常复杂。
    • 你能告诉我你在查询方面的想法,这样我就可以自己做一些研究了吗?
    猜你喜欢
    • 2013-10-23
    • 2014-07-29
    • 2021-08-25
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多