Mysql - 如何查看哪个列匹配?

时间:2013-11-12 23:09:39

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

是否有可能从匹配的地方获取信息?单词,位置或名称?就像一个额外的列,它表示匹配来自的列的名称?

1 个答案:

答案 0 :(得分: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,那么第一个CASE WHEN将返回'word',否则,如果位置匹配,则第二个CASE WHEN将返回'location':kwd,如果name_surname匹配则返回'name_surname'的第三种情况: KWD。然后我使用CONCAT_WS在一个列中合并,它连接三个CASE WHEN,跳过空值。

请注意,如果有多个匹配项,则可能会复制某些行。我会改用这个选择:

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

请参阅简化示例here