限制group_concat中的连接

时间:2013-07-30 12:36:08

标签: mysql

我刚遇到一个我不知道如何解决的问题。它与this(已解决)问题有关。

就像在另一篇文章中提到的那样,我有一个Media表可以保存同一个用户的许多记录,但我只想显示最多六个记录(按顺序,无论如何,只有一张Type 1张图片,后跟最多五张Type张图片。)

只要只有一个Type 1图像,我现在的查询工作正常,但当我添加另一个Type 1图像时,查询会同时显示它们。不幸的是,ORDER BY UserMedia.m_Type = 1 DESC LIMIT 1GROUP_CONCAT之类的内容并不起作用,但这正是我所需要的。谁知道如何实现这个聪明的想法?

我在这里有SQL Fiddle相关代码。我的查询看起来像这样


SELECT
    User.u_UserName, User.u_UserMail, User.u_UserRegistration, 
        Status.us_PaymentStatus, 
        Sex.us_Gender, Sex.us_Interest, 
            Personal.up_Name, Personal.up_Dob, Personal.up_City, Personal.up_Province, 
            UserMedia.m_Id, UserMedia.m_Type, SUBSTRING_INDEX(
                GROUP_CONCAT(
                    CONCAT(
                        UserMedia.m_Type, ':', UserMedia.m_File
                    )
                    ORDER BY UserMedia.m_Type = 1, UserMedia.m_Date DESC SEPARATOR '|'
                ),'|',6
            ) AS userFiles 
FROM User AS User
    JOIN User_Status AS Status ON Status.User_u_UserId = User.u_UserId
    JOIN User_Sex_Info AS Sex ON Sex.User_u_UserId = User.u_UserId
        LEFT JOIN User_Personal_Info AS Personal ON Personal.User_u_UserId = User.u_UserId
        LEFT JOIN Media AS UserMedia ON UserMedia.User_u_UserId = User.u_UserId
WHERE User.u_UserId = '18'
    GROUP BY User.u_UserId

1 个答案:

答案 0 :(得分:0)

散步并带来以下解决方案。也许不是最美丽的,但至少它有效。我也意识到我不需要CONCAT函数


SELECT
    User.u_UserName, User.u_UserMail, User.u_UserRegistration, 
        Status.us_PaymentStatus, 
        Sex.us_Gender, Sex.us_Interest, 
            Personal.up_Name, Personal.up_Dob, Personal.up_City, Personal.up_Province, 
            UserMedia.m_Id, UserMedia.m_Type, SUBSTRING_INDEX(
                GROUP_CONCAT(
                    UserMedia.m_File
                        ORDER BY UserMedia.m_Type = 1 DESC 
                        SEPARATOR '|'
                ),'|',1
            ) AS userFiles, 
            SUBSTRING_INDEX(
                GROUP_CONCAT(
                    UserMedia.m_File
                        ORDER BY UserMedia.m_Date DESC 
                        SEPARATOR '|'
                ),'|',5
            ) AS userTypes, 
            SUBSTRING_INDEX(
                GROUP_CONCAT(
                    Interests.ui_Interest SEPARATOR '|'
                ),'|',5
            ) AS userInterests
FROM User AS User
    JOIN User_Status AS Status ON Status.User_u_UserId = User.u_UserId
    JOIN User_Sex_Info AS Sex ON Sex.User_u_UserId = User.u_UserId
        LEFT JOIN User_Personal_Info AS Personal ON Personal.User_u_UserId = User.u_UserId
        LEFT JOIN Media AS UserMedia ON UserMedia.User_u_UserId = User.u_UserId
        LEFT JOIN User_Interest_Info AS Interests ON Interests.User_u_UserId = User.u_UserId
WHERE User.u_UserId = :uId
    GROUP BY User.u_UserId