2014-04-01 55 views
1

我想創建一個查詢與來自其他表,例如值一起插入幾個值:如何使用多值和SELECT語句插入?

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') 

然而,這給了我一個錯誤,並且從PHP 500內部服務器錯誤。請幫助。

回答

1
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' 

應該這樣做,我認爲......

+0

作品唯一的問題是日期沒有被插入,任何想法? – polymorph

+0

嘗試在php中將它的日期格式發送到mysql之前... –

+0

會不會,謝謝。我會投你一票,但沒有足夠的分數。 – polymorph

0

我敢肯定你需要VALUESSELECT如果你正在做這種方式。試試這個,看看它是否有效。

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' 
相關問題