2014-01-20 43 views
1

查詢中的一列得到一個錯誤的工作就好了,如:與UNION查詢MySQL和我在我選擇

$query = '(SELECT contenttype, id, title, type, image, rating, date2, num_votes FROM videos) 
UNION 
(SELECT contenttype, id, title, type, image, rating, date2, num_votes FROM games) 
UNION 
(SELECT contenttype, id, title, type, image, rating, date2, num_votes FROM pics) 
ORDER BY date2 DESC 
LIMIT 10'; 
$r = mysql_query($query) or die(mysql_error()); 

但如果我嘗試拉柱將無法正常工作,。數據庫中的所有表都使用上名爲的列。我得到這個錯誤:你的SQL語法有錯誤;檢查對應於你的MySQL服務器版本「上,類型,圖像,評分,DATE2,NUM_VOTES從視頻中)UNION(SELECT contentty」在行的我加入

例如使用附近的正確語法手冊在我查詢:

$query = '(SELECT contenttype, id, title, type, on, image, rating, date2, num_votes FROM videos) 
UNION 
(SELECT contenttype, id, title, type, on, image, rating, date2, num_votes FROM games) 
UNION 
(SELECT contenttype, id, title, type, on, image, rating, date2, num_votes FROM pics) 
ORDER BY date2 DESC 
LIMIT 10'; 
$r = mysql_query($query) or die(mysql_error()); 

沒有道理給我爲什麼會出現這種情況

回答

1

ON是在MySQL a reserved keyword引用它應該工作即:。

(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM videos) 
UNION 
(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM games) 
UNION 
(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM pics) 
ORDER BY date2 DESC 
LIMIT 10 
+0

你的岩石之一!謝謝。我實際上曾經以這種方式引用它們。很棒! – user3207931

2

逃脫on領域,因爲它的的MySQL's reserved keywords

$query = '(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM videos) 
UNION 
(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM games) 
UNION 
(SELECT contenttype, id, title, type, `on`, image, rating, date2, num_votes FROM pics) 
ORDER BY date2 DESC 
LIMIT 10'; 
+0

你搖滾!謝謝。我實際上曾經以這種方式引用它們。很棒! – user3207931