Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

sql - Using INSERT INTO with 'SELECT' to supply some values but not others (Access 2010)

I have two tables that look like this:

('MASTER_EOD' TABLE)
ID  SHA1_HEX    ROLE
----------------------------
1   ff34bb03    2
2   eef0a005    1



('ROLE_INDEX' TABLE)
ROLE_NUM    ROLE_NAME
--------------------------
 1           Welcome Calls
 2           Follow Up
 3           Outbound

It should be noted that ROLE is joined to ROLE_NUM in the ROLE_INDEX table.

I am trying to write an amend query where I can pass a string from ROLE_NAME (such as 'Follow Up', 'Outbound') etc. and it's associated ROLE_NUM will be put into the 'ROLE' column.

I've tried to accomplish this with the following query, as a test;

INSERT INTO master_eod ( sha1_hex, role )
VALUES ('ef03ff03',(SELECT role_num FROM role_index WHERE role_name='Follow Up'));

But I get the following error: Query input must contain at least one table or query.

However, if I put the SELECT role_num FROM role_index WHERE role_name='Follow Up' into it's own query, it works.. Likewise, if I the whole SELECT part with a raw value such as 3, it works.

What am I missing? I think I might need to use 'INNER JOIN' somehow but I'm still learning the basics of SQL and can't wrap my head around this particular problem and why Access is throwing the error that it does.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try doing it in the most standard way in SQL, by using the SELECT as the whole source in the INSERT instead of just a single column sub-query:

INSERT INTO master_eod ( sha1_hex, role )
SELECT 'ef03ff03', role_num FROM role_index WHERE role_name='Follow Up' ;

Note that you must ensure that such a query (the SELECT alone) returns just a single row, otherwise you would end up inserting many rows at once in a single go, one for each role_num found (which may or may not be desirable).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...