如何获取匹配列的名称? (例如姓名/类型/国家/城市)
我的表是:
USER
ID int
NAME varchar
TYPE varchar
COUNTRY varchar
CITY varchar
我的sql:
SELECT *
FROM USER
WHERE NAME LIKE '%".$search."%'
OR TYPE LIKE '%".$search."%'
OR COUNTRY LIKE '%".$search."%'
OR CITY LIKE '%".$search."%'
答案 0 :(得分:3)
你可以这样做:
SELECT *
, COALESCE(
CASE WHEN NAME LIKE '%".$search."%' THEN 'name' END
, CASE WHEN NAME TYPE '%".$search."%' THEN 'type' END
, CASE WHEN COUNTRY LIKE '%".$search."%' THEN 'country' END
, CASE WHEN CITY LIKE '%".$search."%' THEN 'city' END
) as matched
FROM USER
WHERE NAME LIKE '%".$search."%'
OR TYPE LIKE '%".$search."%'
OR COUNTRY LIKE '%".$search."%'
OR CITY LIKE '%".$search."%'
如果单个行匹配多个列,matched
将返回一个名称,该名称对应于按{name, type, country, city}
顺序匹配的第一列。
答案 1 :(得分:0)
以下是一种方法,即将OR
扩展为明确指定哪个列匹配的UNION
:
SELECT ..., GROUP_CONCAT(Match) as Match
FROM
(
SELECT ..., 'Name' as Match
FROM USER WHERE
NAME LIKE '%".$search."%'
UNION
SELECT ..., 'Type' as Match
FROM USER WHERE
TYPE LIKE '%".$search."%'
UNION
SELECT ..., 'Country' as Match
FROM USER WHERE
COUNTRY LIKE '%".$search."%'
UNION
SELECT ..., 'City' as Match
FROM USER WHERE
CITY LIKE '%".$search."%'
) x
GROUP BY ...
根据Frazz的评论,需要使用包装器分组来消除Match
列创建的重复项,否则会阻止UNION
的默认不同行为。