2014-01-23 45 views
-1
SELECT * FROM 
(
SELECT messages.from AS `from`, messages.creation AS `creation`, account_images.profile AS `profile`, bio.user_full_name AS `user_full_name` 
FROM messages 
INNER JOIN account_images ON account_images.uuid=messages.from 
INNER JOIN bio ON bio.uuid=messages.from 
WHERE messages.to='{$user}' 
ORDER BY `creation` DESC 
) 
GROUP BY `from` 

爲什麼這個查詢不起作用?嵌套select語句有什麼問題嗎?請幫助我如何解決這個問題...MySQL查詢不能使用嵌套選擇

回答

0

FROM是一個MySQL保留關鍵字使用從列名應該是在backtics否則你會得到錯誤messagesfrom

SELECT * FROM 
(
SELECT messages.`from` AS `from`, messages.creation AS `creation`, account_images.profile AS `profile`, bio.user_full_name AS `user_full_name` 
FROM messages 
INNER JOIN account_images ON account_images.uuid=messages.`from` 
INNER JOIN bio ON bio.uuid=messages.`from` 
WHERE messages.to='{$user}' 
ORDER BY `creation` DESC 
) 
GROUP BY `from` 

Reserved Words

+0

不,它的工作沒有嵌套選擇語句..我希望消息的最後結果,爲什麼我可以試試這個。 – user3222855

0

除了不帶引號的from問題,連接是在錯誤的順序。你不能指表別名在on子句被定義之前,你需要在子查詢表別名:

SELECT * 
FROM (SELECT messages.from AS `from`, messages.creation AS `creation`, 
      account_images.profile AS `profile`, bio.user_full_name AS `user_full_name` 
     FROM account_images INNER JOIN 
      bio 
      ON bio.uuid = messages.`from` INNER JOIN 
      messages 
      ON account_images.uuid = messages.`from` 
     WHERE messages.to='{$user}' 
     ORDER BY `creation` DESC 
    ) t 
GROUP BY `from`; 

最後,想嘗試使用明確描述的技術來獲得一組的最後一條消息因爲在group by擴展的MySQL文檔中不可靠(請參閱here)。