简体   繁体   English

如何使用多值和SELECT语句插入?

[英]How to insert using mutiple values and SELECT statements?

I would like to create a query to insert several values along with values that come from other tables, for example: 我想创建一个查询来插入几个值以及来自其他表的值,例如:

INSERT INTO table
(date, user_id, category_id, title, description)
VALUES
    ((STR_TO_DATE('04-01-2014', '%b-%d-%Y'), 
    (SELECT id FROM users WHERE username = 'admin' LIMIT 1),
    (SELECT id FROM categories WHERE category = 'games' LIMIT 1),
    'title here',
    'description here')

This however, gives me an error and from PHP a 500 internal server error. 但是,这给了我一个错误,并且从PHP出现了500个内部服务器错误。 Help please. 请帮助。

INSERT INTO table (fields)
SELECT
    str_to_date(),
    users.id,
    categories.id,
    'title',
    'description' 
FROM
    users 
INNER JOIN
    categories ON users.key = categories.key
WHERE
    users.username = 'admin' AND
    categories.category = 'games'

that should do it I think... 我认为应该做到的...

I'm pretty sure you need a SELECT after VALUES if you're doing it this way. 我很确定如果这样做的话,您需要在VALUES之后进行SELECT Try this and see if it works. 试试这个,看看是否可行。

INSERT INTO table
(date, user_id, category_id, title, description)
VALUES
SELECT 
  STR_TO_DATE('04-01-2014', '%b-%d-%Y'), 
  (SELECT id FROM users WHERE username = 'admin' LIMIT 1),
  (SELECT id FROM categories WHERE category = 'games' LIMIT 1),
  'title here',
  'description here'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM