Mysql:ORDER BY加入了表列

时间:2011-08-20 08:22:47

标签: mysql

        SELECT 
            u.*,
            ur.friend_id,
            COUNT(
                IF(um.to_user_id = ?,
                    (IF(um.`date` >= ulr.last_read,um.message_id,NULL))
                ,NULL)
            ) as new_messages
            ,i.t_1 AS user_photo
        FROM user_relationships ur
        LEFT JOIN `user` u ON u.user_id=ur.friend_id
        LEFT JOIN user_messages um ON um.from_user_id=ur.friend_id
        LEFT JOIN user_last_read ulr ON ulr.read_who=ur.friend_id

        LEFT JOIN ads a ON a.user_id=u.user_id
        LEFT JOIN images i ON a.id=i.ad_id

        WHERE ur.user_id=?
        GROUP BY ur.friend_id
        ORDER BY new_messages DESC

我需要这个部分i.t_1 AS user_photo处于DESC顺序,因为可以有多个user_photos,我需要选择最新的部分。

我使用GROUP_CONCAT(i.t_1 ORDER BY i.image_id DESC) AS user_photo的旧解决方案。 但我只需要一个图像,而不是所有可用的图像。 :)

谢谢;)

2 个答案:

答案 0 :(得分:0)

如果没有查看表创建语句,很难100%确定,但这样的事情应该有效:

GROUP BY ur.friend_id, i.ad_id ORDER BY new_messages DESC, i.t_1 DESC

顺便说一下,我觉得你的数据库太苛刻了。从查询到应用程序提取一些逻辑,脚本语言通常可以比数据库引擎更好。

答案 1 :(得分:0)

SELECT 
    u.*,
    ur.friend_id,
    COUNT(
        IF(um.to_user_id = ?,
            (IF(um.`date` >= ulr.last_read,um.message_id,NULL))
        ,NULL)
    ) as new_messages,
    (
        SELECT t_1 
        FROM images 
        WHERE ad_id = a.id 
        ORDER BY t_1 DESC 
        LIMIT 1
    ) AS user_photo
FROM 
    user_relationships ur
    LEFT JOIN `user` u ON u.user_id=ur.friend_id
    LEFT JOIN user_messages um ON um.from_user_id=ur.friend_id
    LEFT JOIN user_last_read ulr ON ulr.read_who=ur.friend_id
    LEFT JOIN ads a ON a.user_id=u.user_id
WHERE ur.user_id=?
GROUP BY ur.friend_id
ORDER BY new_messages DESC