mysql查询 - 发出重复结果

时间:2013-11-13 08:25:02

标签: mysql sql

我有这个问题:

SELECT DISTINCT u.name_surname, u.avatar, u.location
FROM users AS u
JOIN connections AS c
  ON c.user_id = u.id
JOIN words_en AS w 
  ON w.id = c.word_id
LEFT JOIN friends AS f1
  ON f1.asker_user_id = :user_id
    AND f1.status = 1
    AND f1.asked_user_id = u.id
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND (u.privacy = 3 OR (u.privacy = 2 and f1.id IS NOT NULL))
AND c.deleted <> 1

我想知道kwd来自哪个匹配(哪一列),

所以我在select中添加了这个:

/*,
    CONCAT_WS(",",
        CASE WHEN w.word = :kwd THEN "word" END,
        CASE WHEN u.location = :kwd THEN "location" END,
        CASE WHEN u.name_surname = :kwd THEN "name_surname" END) As matches*/

添加此问题后的问题是,无论何时存在双重匹配,都要说明位置和名称,而不是显示两个结果。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

尝试对此附加字段使用GROUP BY而不是DISTINCTMAX

SELECT u.name_surname, u.avatar, u.location, 
       MAX(CONCAT_WS(",",
        CASE WHEN w.word = :kwd THEN "word" END,
        CASE WHEN u.location = :kwd THEN "location" END,
        CASE WHEN u.name_surname = :kwd THEN "name_surname" END)) As matches
FROM users AS u
JOIN connections AS c
  ON c.user_id = u.id
JOIN words_en AS w 
  ON w.id = c.word_id
LEFT JOIN friends AS f1
  ON f1.asker_user_id = :user_id
    AND f1.status = 1
    AND f1.asked_user_id = u.id
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND (u.privacy = 3 OR (u.privacy = 2 and f1.id IS NOT NULL))
AND c.deleted <> 1

GROUP BY u.name_surname, u.avatar, u.location