2013-02-14 125 views
3

以下是我目前正在不過我收到一個MySQL錯誤:INSERT與兩個SELECT語句

mysql_query ("INSERT INTO profile_tag (profile_id, tag_id) 
(SELECT profile_id FROM profile WHERE username = '$username'), 
(SELECT tag_id FROM tag WHERE tag = '$music' OR tag = '$sports' OR tag = '$tech')"); 

我能夠完成INSERT使用單一SELECT聲明然而,不是兩個。

錯誤我收到:

Query is invalid: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')' at line 1

+2

顯示我們的錯誤可能會有所幫助:-) – 2013-02-14 03:50:40

+2

[**請不要使用新的'mysql_ *'功能代碼**](http://bit.ly/phpmsql)。他們不再被維護[並且被正式棄用](http://j.mp/XqV7Lp)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 – Eric 2013-02-14 03:51:29

+0

不再推薦使用「mysql」。你應該使用'mysqli_query(...)'http://php.net/manual/en/mysqli.query.php – 2013-02-14 03:51:36

回答

3

很像錯誤說,語法不正確。插入的值必須與列定義中的值的數量相匹配。

INSERT INTO profile_tag (profile_id, tag_id) 
SELECT 
    profile_id, tag_id 
FROM 
    profile 
    CROSS JOIN tag 
WHERE 
    username = ? 
    AND tag IN (?, ?, ?) 

注意,這將插入行如果tag值,發現每個輸入,但我相信這是你想要的。

+0

這幾乎完成了這項工作!當第一次運行查詢時,它能夠正常工作,第二次我在表中的輸出不像我預期的那樣。配置文件1的標籤2和3正確顯示。然後當再次運行帶有標籤1和3的配置文件2時,輸出會提供帶有標籤1,1,3,3的配置文件1,2,1,2? – rp7 2013-02-14 04:14:28

+0

@ user1888378我很難說,除非你給我具體的查詢和表格內容 – 2013-02-14 04:15:26

+0

對不起!它確實有效,我的測試導致我不小心保留了用戶名,因此弄亂了數字。謝謝! – rp7 2013-02-14 04:25:17

1

您可以使用VALUES條款

insert into profile_tag(user_id, tag_id) values 
((select id from users where username = 'alice'), 
(select id from tags where tag = 'music')); 

http://sqlfiddle.com/#!2/76439/1/0

0
mysql_query ("INSERT INTO profile_tag (profile_id, tag_id) 
(SELECT profile.profile_id, tag.tag_id FROM profile LEFT JOIN tag ON 1 WHERE profile.username = '$username' AND tag.tag IN ('$music', '$sports', '$tech'))");