你可以使用这样的东西:
SELECT DISTINCT
u.name_surname,
u.avatar,
u.location,
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
WHERE (w.word = :kwd
OR u.location = :kwd
OR u.name_surname = :kwd)
AND u.privacy > 0
AND c.deleted <> 1
如果 w.word = :kwd 或 null 否则,第一个 CASE WHEN 将返回 'word',如果位置匹配 :kwd,第二个 CASE WHEN 将返回 'location',如果 name_surname 匹配 :kwd,则第三种情况将返回 'name_surname'。然后,我使用连接三个 CASE WHEN 的 CONCAT_WS 在单个列中组合,跳过空值。
请注意,如果有多个匹配项,某些行可能会重复。我会改用这个选择:
SELECT
u.name_surname,
u.avatar,
u.location,
GROUP_CONCAT(
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
...your from...
WHERE
...your where...
GROUP BY
u.name_surname,
u.avatar,
u.location
请在此处查看简化示例。