1

I've this query:

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

I wanted to understand where match for kwd was coming from (which column),

so I added this in 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*/

Problem after adding this is that whenever there is a double match, lets say both in location and name, than two results are displayed. How do i solve this?

4

1 回答 1

1

尝试使用 GROUP BY 代替DISTINCTandMAX用于这个附加字段:

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
于 2013-11-13T08:32:57.237 回答