【问题标题】:Ignore null entries in sql忽略sql中的空条目
【发布时间】:2018-04-10 13:33:07
【问题描述】:

下面的示例构建了一个表,该表通过 userId 和 PassageId 提取前两个得分值。如何仅选择新表中每条记录至少包含两个分数的记录(即忽略 score2 为空的记录)?

Example

代码:

 drop table if exists simon;
 drop table if exists simon2;
 Create table simon (userId int, passageId int, score int);
 Create table simon2 (userId int, passageId int, score1 int,score2 int);    

 INSERT INTO simon (userId , passageId , score )
 VALUES
 (10, 1, 2),
 (10, 1, 3),
 (10, 2, 1),
 (10, 2, 1),
 (10, 2, 5),
 (11, 1, 1),
 (11, 2, 2),
 (11, 2, 3),
 (11, 3, 4);

 insert into simon2(userId,passageId,score1,score2)
 select t.userId, t.passageId,
 substring_index(t.scores,',',1) as score1,
 (case when length(t.scores) > 1 then substring_index(t.scores,',',-1) 
  else null
  end
 ) as score2
 from 
 (select userId,passageId,
 substring_index (group_concat(score separator ','),',',2) as scores
 from simon
 group by userId,passageId) t;

 select *from simon2;

这是我现在得到的:

   userId   passageId   score1  score2
1   10      1           2       3
2   10      2           1       1
3   11      1           1       NULL
4   11      2           2       3
5   11      3           4       NULL

这就是我想要的:

   userId   passageId   score1  score2
1   10      1           2       3
2   10      2           1       1
4   11      2           2       3

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    只需在您的查询周围添加此内容

    Select * from ( ...... ) x where score2 is not null 
    

    【讨论】:

    • #1064 - 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在 'insert into simon2(userId,passageId,score1,score2) 附近使用的正确语法
    【解决方案2】:

    您没有指定score_1score_2 的分数的顺序,所以我将只使用min()max()。然后,您可以按以下方式执行逻辑:

    select s.userid, s.passageid,
           max(score) as score_1, max(score) as score_2
    from simon s
    group by s.userid, s.passageid
    having count(*) >= 2;
    

    这并不能为 10/2 提供完全相同的结果。但是,您的结果是任意的,因为 group_concat() 没有排序依据。 SQL 表代表 无序 集合。除非您指定,否则没有排序。

    如果要排序,则将表定义为:

    Create table simon (
        simonId int auto_increment primary key,
        userId int,
        passageId int,
        score int
    );
    

    然后适当地使用simonId 列。

    【讨论】:

    • 如果我按照您的建议添加排序,如何忽略空条目?
    • 请澄清您的评论。首先,你的意思是什么:“这不会给你 10/2 的完全相同的结果。”其次,请您检查您提供的解决方案代码。我添加了您建议的 auto_increment,并尝试了您的代码,但无法使其正常工作。
    • @SimonRH 。 . .我的代码很好:rextester.com/JYF12871。破坏的是你的代码。
    • 我很困惑,你说是我的代码坏了,但你发布的链接又回到了我的代码。您的意思是链接到更正的帖子吗?我还看到了您的评论:“然后适当地使用 simonId 列。”我的问题是我不确定如何使用 auto_increment 来解决问题。
    • 请说明我应该如何使用您的代码。我试图使用 rextexter 链接中的代码,但显然做错了。我想使用您的解决方案,但完全卡住了,不知道如何前进。
    猜你喜欢
    • 2022-08-02
    • 2021-03-07
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多