如何在mysql中分组而不显示重复项?

时间:2017-08-22 06:34:31

标签: php mysql

我正在为保姆列表构建一个搜索页面,用户可以根据工资,距离和评级过滤结果。一切正常,但即使只有2个人或1个人,我得到三到四个结果,我无法弄明白。

这是我的问题:

SELECT `users`.`id`                        AS `user_id`, 
       `user_wage_preferences`.`one_child` AS `wage`, 
       `user_contact_informations`.`lat`, 
       `user_contact_informations`.`lng`, 
       `user_reviews`.`rating`, 
       Sum(user_reviews.recommended)       AS recommended, 
       ( 6371 * Acos(Cos(Radians(59.448355500000005)) * Cos(Radians(lat)) * Cos( 
                                   Radians(lng) - Radians(24.7406023)) + 
                              Sin(Radians(59.448355500000005)) * Sin( 
                              Radians(lat))) ) 
                                           AS distance 
FROM   `users` 
       LEFT JOIN `user_reviews` 
              ON `users`.`id` = `user_reviews`.`nanny_id` 
       INNER JOIN `user_wage_preferences` 
               ON `users`.`id` = `user_wage_preferences`.`user_id` 
       INNER JOIN `user_contact_informations` 
               ON `users`.`id` = `user_contact_informations`.`user_id` 
WHERE  `users`.`role` = ? 
       AND `users`.`account_status` = ? 
       AND `users`.`id` IN ( ?, ? ) 
GROUP  BY `user_id`, 
          `user_contact_informations`.`lat`, 
          `user_contact_informations`.`lng`, 
          `user_reviews`.`rating`, 
          `user_wage_preferences`.`one_child` 
HAVING `recommended` > ? 
ORDER  BY `recommended` DESC 

在我的json回复中,我看到了:

[  
    {  
        "user_id":1,
        "wage":"6",
        "lat":59.44,
        "lng":24.74,
        "rating":5,
        "recommended":"1",
        "distance":0.92971285651468
    },
    {  
        "user_id":4,
        "wage":"4",
        "lat":59.46,
        "lng":24.83,
        "rating":5,
        "recommended":"1",
        "distance":5.2153552636895
    },
    {  
        "user_id":1,
        "wage":"6",
        "lat":59.44,
        "lng":24.74,
        "rating":4,
        "recommended":"0",
        "distance":0.92971285651468
    },
    {  
        "user_id":4,
        "wage":"4",
        "lat":59.46,
        "lng":24.83,
        "rating":1,
        "recommended":"1",
        "distance":5.2153552636895
    }
]

如您所见,我得到user_id 1user_id 4两次。我无法弄清楚如何通过user id删除重复项或组。

我在这里做错了什么?如何向用户显示一次? 我使用laravel作为框架。

1 个答案:

答案 0 :(得分:1)

您的结果有不同的评分。

我可以看到user1的评分为4,5。如果你删除评级,你将只获得一个记录。

此外,您可以使用群组联系人以逗号分隔字符串获取多个评分 - GROUP_CONCAT(评级ORDER BY评级ASC)