初学SQL问题。假设我有两张桌子
表1
ID name1 name2 name3
-- ----- ----- -----
1 blah1 high south
2 blah2 low north
3 blah3 high north
4 blah4 low south
表2
ID head1 head2
-- ----- ----------
1 blah5 super high south
2 blah6 medium high northern
3 blah7 kind of low north
4 blah8 kind of low south
现在我想将table2
的记录添加到table1
。但列name2
和name3
的数据合并在head2
table1
的字符串中。所以我想从head2' and put them in
table1'中提取这些字段,使它看起来像这样
表1
ID name1 name2 name3
-- ----- ----- -----
1 blah1 high south
2 blah2 low north
3 blah3 high north
4 blah4 low south
5 blah5 high south
6 blah6 high north
7 blah7 low north
8 blah8 low south
现在我想到了某种IF
语句(但不知道如何在SQL中实现它)
for each record in table2 do
table1.name1.insert(head1)
if table2.head2 == "super high south" then
table1.name2.insert(high)
table1.name3.insert(south)
if table2.head2 == "medium high northern" then
table1.name2.insert(high)
table1.name3.insert(north)
etc....
在我的实际应用程序中,head2
中的唯一字符串类型数量有限,因此每个字符串的if语句都是可行的
您如何编写SQL查询(对于Microsoft Access)来执行此操作?
答案 0 :(得分:0)
使用有限数量的[head2]值,您可以使用Switch()
函数编写“if语句”逻辑,如下所示:
INSERT INTO table1 (name1, name2, name3)
SELECT
head1 AS name1,
Switch(
head2="super high south", "high",
head2="medium high northern", "high",
head2="kind of low north", "low",
head2="kind of low south", "low")
AS name2,
Switch(
head2="super high south", "south",
head2="medium high northern", "north",
head2="kind of low north", "north",
head2="kind of low south", "south")
AS name3
FROM table2