MySQL使用select子查询插入一个值

时间:2012-03-12 17:34:49

标签: mysql

我有一个MySQL插入查询,需要从另一个表中提取一个数据字段,我想知道是否可以使用select子查询完成此操作

INSERT INTO resources
(
     client_account_id,
     date_time,
     resource_name,
     resource_description_id,
)
VALUES
(
      {0},
      '{1}',
      '{2}',
      {3},
 )

我需要一个select查询来从另一个表中获取resource_description_id

SELECT resource_description_id 
FROM resource_descriptions 
WHERE resource_description = '{0}'

我已经看过复制整个表的示例,但是我不确定当另一个表只需要一个字段而其他字段来自表单时如何才能完成。

谢谢!

5 个答案:

答案 0 :(得分:9)

您的子查询可以只选择它需要的值。类似的东西:

INSERT INTO resources
(
     client_account_id,
     date_time,
     resource_name,
     resource_description_id,
)
SELECT {0}, '{1}','{2}', resource_description_id 
FROM resource_descriptions 
WHERE resource_description = '{3}'

答案 1 :(得分:2)

INSERT INTO resources
(
 client_account_id,
 date_time,
 resource_name,
 resource_description_id,
)
VALUES
(
  {0},
  '{1}',
  '{2}',
  SELECT resource_description_id 
FROM resource_descriptions 
WHERE resource_description = '{0}'
 )

答案 2 :(得分:1)

INSERT INTO resources
(
     resource_description_id
)
(
SELECT resource_description_id 
FROM resource_descriptions 
WHERE resource_description = '{0}'
)

答案 3 :(得分:0)

您可以使用选择查询的结果进行插入

INSERT INTO resources
(
 client_account_id,
 date_time,
 resource_name,
 resource_description_id
)
SELECT 
  '{0}',
  '{1}',
  '{2}',
  resource_description_id
FROM resource_descriptions 
WHERE resource_description = '{0}'

答案 4 :(得分:0)

除非我在子查询周围添加括号,否则MySQL并不喜欢大多数这些查询。这是我使用的。

INSERT INTO resources
(
 client_account_id,
 date_time,
 resource_name,
 resource_description_id,
)
VALUES
(
  '{0}',
  '{1}',
  '{2}',
  (SELECT resource_description_id 
   FROM resource_descriptions 
   WHERE resource_description = '{0}')
)