我对SQL很陌生,我很难看到我在这个剧本中错过了什么。
每次我尝试运行它时,都会花费很长时间并因内存不足而导致错误。
select r.CONSTITUENT_ID
, case when r.SEX = '1'then 'Male'
when r.SEX = '2' then 'Female' else 'Unknown'end as Gender
, case when r.KEY_INDICATOR = 'O' then 'Organisation'
when r.KEY_INDICATOR = 'I' then 'Individual'end as record_Classification
, case when cc.CODE = '1924' then 'Bristol Affiliated'
when cc.CODE = '1963' then 'Gloucester Affiliated'
when cc.CODE = '2045' then 'Wiltshire Affiliated'
else 'n/a' end as DW_Affiliation
from RECORDS r, CONSTITUENT_CODES cc
答案 0 :(得分:2)
这个
from RECORDS r,CONSTITUENT_CODES cc`
是交叉连接,意味着show me every row from RECORDS with every row CONSTITUENT_CODES
,因此它返回[来自RECORDS的行数] * [来自CONSTITUENT_CODES的行数]行。
您必须使用join
或where
来消除cross join
from RECORDS r,CONSTITUENT_CODES cc
where r.column = cc.column
或
from RECORDS r
join CONSTITUENT_CODES cc on r.column = cc.column
我不知道你的桌子结构,但也许这会起作用
select r.CONSTITUENT_ID
, case when r.SEX = '1'then 'Male'
when r.SEX = '2' then 'Female' else 'Unknown'end as Gender
, case when r.KEY_INDICATOR = 'O' then 'Organisation'
when r.KEY_INDICATOR = 'I' then 'Individual'end as record_Classification
, case when cc.CODE = '1924' then 'Bristol Affiliated'
when cc.CODE = '1963' then 'Gloucester Affiliated'
when cc.CODE = '2045' then 'Wiltshire Affiliated'
else 'n/a' end as DW_Affiliation
from RECORDS r, CONSTITUENT_CODES cc
where r.CONSTITUENT_ID = cc.CONSTITUENT_ID
使用推荐的连接样式,它看起来像
select r.CONSTITUENT_ID
, case when r.SEX = '1'then 'Male'
when r.SEX = '2' then 'Female' else 'Unknown'end as Gender
, case when r.KEY_INDICATOR = 'O' then 'Organisation'
when r.KEY_INDICATOR = 'I' then 'Individual'end as record_Classification
, case when cc.CODE = '1924' then 'Bristol Affiliated'
when cc.CODE = '1963' then 'Gloucester Affiliated'
when cc.CODE = '2045' then 'Wiltshire Affiliated'
else 'n/a' end as DW_Affiliation
from RECORDS r
join CONSTITUENT_CODES cc on r.CONSTITUENT_ID = cc.CONSTITUENT_ID
我在RECORDS
CONSTITUENT_ID
中看到此列可用于加入来自CONSTITUENT_CODES
的列ID - 我猜CONSTITUENT_ID