请帮我解决下面解释的情况:
ID name address age hobby GPA
---------------------------------------------------------
101 James 100 Garfield St 21 reading 3.13
101 James 100 Garfield St 21 writing 2.63
101 James 100 Garfield St 21 running 3.81
109 Tom 19 Lily Ave 19 dating 3.54
109 Tom 20 Lily Ave 19 climbing 2.76
109 Tom 21 Lily Ave 19 watching 3.91
我想复制具有相同ID的行集(例如101),并通过运行单个sql查询为每个集分配一个State缩写。例如:将状态CA,NJ和DE添加到ID为101的行,结果集应如下所示:
ID name address age hobby GPA state
-----------------------------------------------------------------------
101 James 100 Garfield St 21 reading 3.13 CA
101 James 100 Garfield St 21 writing 2.63 CA
101 James 100 Garfield St 21 running 3.81 CA
101 James 100 Garfield St 21 reading 3.13 NJ
101 James 100 Garfield St 21 writing 2.63 NJ
101 James 100 Garfield St 21 running 3.81 NJ
101 James 100 Garfield St 21 reading 3.13 DE
101 James 100 Garfield St 21 writing 2.63 DE
101 James 100 Garfield St 21 running 3.81 DE
请记住,其他所有内容都与添加州缩写之前的方式相同。还假设我有三个以上的状态要添加并集成到查询中,比方说,我有50个状态。感谢您提前花时间和精力!
答案 0 :(得分:0)
这应该产生结果集:
select x.*, y.st
from tbl x
join
(select 'CA' as st union all
select 'NJ' union all
select 'DE') y
where x.id = 101
答案 1 :(得分:0)
创建一个包含ID和状态的新表
ID ST
101 CA
101 NJ
101 DE
109 ..
然后加入你的桌子
SELECT t.*, s.st
FROM tbl t
JOIN states s ON t.id = s.id