2013-03-05 241 views
-3

我正在從多個表中提取數據。 並試圖solve this將兩個查詢合併爲一個

最後我得到兩個查詢

1),其獲取用戶信息的培訓相關的數據。

2)獲取所有評論及其細節。

我想在一個查詢中組合這兩個查詢。

查詢1)

SELECT user_messages.messageid,user_messages.message, 
user_messages.sentby,user_messages.visibility, 

GROUP_CONCAT(post_images.image_id SEPARATOR ';') 
AS `POST_IMG_ID`, 


GROUP_CONCAT(post_images.small_pic_path SEPARATOR ';') 
AS 'POST_IMG_PATH', 

(
    SELECT count(*) FROM likes 
    WHERE element_id=user_messages.messageid 
)AS 'TOTAL_LIKES', 

smsusers.fname as 'SENTBY_FNAME', 
smsusers.lname as 'SENTBY_LNAME', 
profile_pic.small_pic_path as 'SENTBY_SMALL_PIC_PATH' 

FROM user_messages 
     INNER JOIN smsusers ON 
     user_messages.SENTBY = smsusers.id 
INNER JOIN profile_pic ON 
user_messages.SENTBY = profile_pic.userid 
left outer JOIN post_images ON 
user_messages.messageid=post_images.messageid 
WHERE user_messages.userid='1' 
GROUP BY user_messages.messageid 
order by user_messages.adddate 

其工作環節Sql Fiddle

查詢2)

SELECT comments.comment_id, comments.comment, comments.comment_date, 
smsusers.fname ,smsusers.lname,profile_pic.small_pic_path 
FROM comments, smsusers , profile_pic , user_messages 
WHERE user_messages.messageid = 'm1' 
AND user_messages.userid = smsusers.id 
AND smsusers.id = profile_pic.userid 
ORDER BY comment_date 
LIMIT 0, 10; 

工作環節Sql Fiddle

+0

問題是......? – Matten 2013-03-05 11:23:22

+1

你有沒有嘗試過自己,或者你只是想讓別人爲你做你的工作? – fancyPants 2013-03-05 11:26:35

+0

你的需求量是多少? – 2013-03-05 11:37:01

回答

0

使用的部份查詢和刪除相關子查詢

SELECT user_messages.messageid, 
     user_messages.message, 
     user_messages.sentby, 
     user_messages.visibility, 
     GROUP_CONCAT(post_images.image_id SEPARATOR ';') AS `POST_IMG_ID`, 
     GROUP_CONCAT(post_images.small_pic_path SEPARATOR ';') AS 'POST_IMG_PATH', 
     likes.TCount AS 'TOTAL_LIKES', 
     smsusers.fname AS 'SENTBY_FNAME', 
     smsusers.lname AS 'SENTBY_LNAME', 
     profile_pic.small_pic_path AS 'SENTBY_SMALL_PIC_PATH', 
     GROUP_CONCAT(comments.comment) AS `Comments` 
FROM user_messages 
INNER JOIN smsusers ON user_messages.SENTBY = smsusers.id 
INNER JOIN profile_pic ON user_messages.SENTBY = profile_pic.userid 
LEFT OUTER JOIN post_images ON user_messages.messageid = post_images.messageid 
LEFT JOIN 
    (SELECT element_id, 
      COUNT(*) AS `TCount` 
    FROM likes 
    GROUP BY element_id) AS likes ON likes.element_id = user_messages.messageid 
LEFT JOIN comments ON comments.comment_on = user_messages.messageid 
WHERE user_messages.userid = '1' 
GROUP BY user_messages.messageid 
ORDER BY user_messages.adddate; 

Fiddle Demo

+0

感謝您的回覆。這裏'POST_IMG_ID'和'POST_IMG_PATH'重複多次 – 2013-03-05 13:17:34

+0

我有一個更多的請求,我們可以根據'comments.comment_date' – 2013-03-05 13:19:58

+0

排序'COMMENTS'我想要獲取'smsusers.fname'和'smsusers.lname '的評論者和'profile_pic.small_pic_path'的評論者 – 2013-03-05 13:35:30