在MATCH()AGAINST()中查找匹配列的名称或别名

时间:2019-10-19 14:26:28

标签: mysql sql mariadb

我正在使用MATCH() AGAINST()在数据库中进行全文搜索。由于我要从多个表中获取数据,因此我创建了VIEW并在MARIADB中使用以下查询格式,

SELECT 
DAT1, DAT2, DAT3 
FROM VIEW1
WHERE 
MATCH (COL1) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) OR
MATCH (COL2) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) OR
MATCH (COL3) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE)

一切正常,但是我正在查询中寻找一个附加输出,即我在其中找到搜索结果的列名

如何在查询的输出中获取匹配字符串的COL1COL2COL3的名称或别名?

2 个答案:

答案 0 :(得分:2)

您可以在case中使用select表达式:

SELECT DAT1, DAT2, DAT3,
       CONCAT_WS(',',
                 (CASE WHEN MATCH(COL1) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0 THEN 'col1' END),
                 (CASE WHEN MATCH(COL2) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0 THEN 'col2' END),
                 (CASE WHEN MATCH(COL2) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0 THEN 'col3' END)
                ) as cols
FROM VIEW1
WHERE MATCH (COL1) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0 OR
      MATCH (COL2) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0 OR
      MATCH (COL3) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) > 0;

答案 1 :(得分:1)

( SELECT DAT1
    FROM tbl1
    WHERE MATCH (COL1) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) )
UNION ALL
( SELECT DAT2
    FROM tbl2
    WHERE MATCH (COL2) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) )
UNION ALL    
( SELECT DAT3
    FROM tbl3
    WHERE MATCH (COL3) AGAINST ('lisa mona aachen' IN NATURAL LANGUAGE MODE) )

UNION ALL的速度比默认设置(UNION DISTINCT快,但是如果可能会出现重复并且您希望将其去重复,请使用DISTINCT

不需要VIEW。或者,您可以在上面的VIEW中输入文本字符串以等待填写(通过@variable?)。