Hive查询左连接得到错误的结果

时间:2016-10-24 07:21:43

标签: hive hql

首先,创建两个表。

CREATE DATABASE IF NOT EXISTS test;
USE test;
DROP TABLE IF EXISTS student_info;
CREATE TABLE IF NOT EXISTS student_info(
id string COMMENT 'student id',
name string COMMENT 'student name'
)
PARTITIONED BY (l_date string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t';
ALTER TABLE test.student_info SET SERDEPROPERTIES('serialization.null.format' = '');

DROP TABLE IF EXISTS student_score;
CREATE TABLE IF NOT EXISTS student_score(
id string COMMENT 'student id',
class string COMMENT 'class',
score int COMMENT 'class score'
)
PARTITIONED BY (l_date string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t';
ALTER TABLE test.student_score SET SERDEPROPERTIES('serialization.null.format' = '');

表student_info中的4条记录,

1   jobs
2   cook
3   gates
4   musk

表student_score中的3条记录,

1   math    98
2   math    96
3   math    94

我希望得到没有分数且身份证明的学生是' 4'

select * from test.student_info a
left join test.student_score b
on a.id=b.id
where (b.id='' or b.id is null)
and a.id='4';

我一无所获。 但是,我添加了' trim()'。

select * from test.student_info a
left join test.student_score b
on a.id=b.id
where (b.id='' or b.id is null)
and trim(a.id)='4';

我能得到我想要的东西。

a.id    a.name  b.id    b.class b.score
4   musk    NULL    NULL    NULL

所以,我认为有一个错误。

3 个答案:

答案 0 :(得分:0)

test.student_info表中的数据似乎在ID之前或之后有空格。这可以解释为什么在a.id='4'为真时trim(a.id)='4'为假。

如果您从文件中加载表格,请检查您是否有额外的空格。

答案 1 :(得分:0)

最好的解决方案是将id的数据类型更改为int 我没有看到你为什么把它作为字符串当我只在你的id中看到整数值时这样你可以确保它们可以在不修剪它们的情况下进行比较

答案 2 :(得分:0)

正如亚历克斯所说,你必须有空位。我尝试了您在类似数据上发布的查询,并获得了所需的结果。

或者您也可以使用以下查询:

select a.id,a.name,a.l_date,b.class,b.score
FROM student_info a left join student_score b
ON a.id=b.id 
where b.score IS NULL;