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?

1 Answer 1

1

Try to use GROUP BY instead of DISTINCT and MAX for this additional field:

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
Sign up to request clarification or add additional context in comments.

1 Comment

1 issue I'm having, and maybe you know how to solve, if user has no 0 entry in connections table, than select returns nothing, even if match is found in location for example :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.