我可以在INSERT查询中使用SELECT子查询吗?

时间:2011-06-10 16:07:00

标签: mysql subquery

我已尝试使用建议here的语法,但它不适用于我的查询。

以下是我目前的情况:

INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant)
        VALUES (288, 2011, 1234, 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel', 'Scottsdale', 'AZ', '2011-01-15', 60, 26, 15, 29, 0, '0', '0', '0', '0', '', NOW(), NOW(), '')

但是,我需要从同一个表中选择entry_code的值 - 我可以将其作为单个查询来执行:

MAX(entry_code) FROM dot WHERE year = 2011

但似乎无法将其与insert语句集成。这可能吗?或者这样的子查询只有在从不同的表中选择时才会起作用吗?

3 个答案:

答案 0 :(得分:2)

INSERT INTO dot (entrant_id, year, entry_code, ...)
SELECT 288, 2011, MAX(entry_code), ... FROM dot WHERE year=2011

答案 1 :(得分:0)

您提供的链接中的语法应该有效。但这不是你“目前拥有”的语法尝试这样的语法(这与该链接非常相​​似......):

insert into dot(field1, field2, field3, field4) select max(entry_code), 'value2', val3, 'value4' from dot where year = 2011

答案 2 :(得分:0)

INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant)
VALUES (288, 2011, (SELECT MAX(entry_code) FROM dot WHERE year = 2011), 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel' ...