0

检查此查询:

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
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND u.privacy > 0
AND c.deleted <> 1

是否可以从匹配的来源获取信息?词、位置或名称?就像一个额外的列,说明匹配来自的列的名称?

4

1 回答 1

1

你可以使用这样的东西:

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

在此处查看简化示例。

于 2013-11-12T23:17:16.327 回答