SQL查询不返回某些行

时间:2014-04-15 14:56:02

标签: sql

我有3张表格如下。

DATA(entity_id, crv_name, data_cnt_id)
PROCESSED_DATA(entity_id, crv_name, run_id)
RUNS(run_id, data_cnt_id)

DATAPROCESSED_DATA都有类似的列,但最后一列除外。 PROCESSED_DATA的行数明显多于DATA

DATA与旧的crv_name值有关,PROCESSED_DATA包含新的crv_name值。

我正在尝试编写一个返回类似内容的查询,用于特定的运行(在RUN_IDPROCESSED_DATA以及RUNS中使用DATA_CNT_ID标识{ {1}}):

DATA

但是,我无法通过下面的查询获得最后一行(即没有旧crv_name的实体,因此不在表+----------------------------------------------------------------+ | PROCESSED_DATA.ENTITY_ID PROCESSED_DATA.CRV_NAME DATA.CRV_NAME | +----------------------------------------------------------------+ | entity123 123_new_name 123_old_name | | entity456 456_new_name 456_old_name | | entity789 789_new_name null | +----------------------------------------------------------------+ 中):

DATA

你能帮我改进一下我的查询吗?

4 个答案:

答案 0 :(得分:2)

您需要外部加入记录:

select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
left join data d on d.entity_id = pd.entity_id 
left join runs r on r.run_id = pd.run_id and r.data_cnt_id = d.data_cnt_id and r.run_id = 7;

如果必须有跑7:

select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
inner join runs r on r.run_id = pd.run_id and r.run_id = 7
left join data d on d.entity_id = pd.entity_id and d.data_cnt_id = r.data_cnt_id;

答案 1 :(得分:0)

join更改为left join

select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
left join data d on d.entity_id = pd.entity_id 
join runs r on r.run_id = pd.run_id and r.data_cnt_id = m.data_cnt_id
where r.run_id = 7

答案 2 :(得分:0)

    select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
join data d on d.entity_id = pd.entity_id 
join runs r on r.run_id = pd.run_id and r.data_cnt_id = m.data_cnt_id
where r.run_id = 7

什么是" m.data_cnt_id",我没有看到像m这样的别名。也许你需要使用:

join runs r on r.run_id = pd.run_id and r.data_cnt_id = d.data_cnt_id

答案 3 :(得分:0)

如果你想要每个新实体

select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
LEFT JOIN data d on d.entity_id = pd.entity_id 
RIGHT join runs r on r.run_id = pd.run_id and r.data_cnt_id = m.data_cnt_id
where r.run_id = 7

如果你想要所有新旧的

select pd.ntt_id, pd.crv_name, d.crv_name
from processed_data pd
FULL JOIN data d on d.entity_id = pd.entity_id 
RIGHT runs r on r.run_id = pd.run_id and r.data_cnt_id = m.data_cnt_id
where r.run_id = 7