忽略sql中的空条目

时间:2017-10-29 13:10:42

标签: mysql sql

下面的示例构建了一个表,该表通过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

2 个答案:

答案 0 :(得分:0)

只需在查询周围添加

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

答案 1 :(得分:0)

您没有指定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列。