1

我有一个包含 4 列的 VIEW,我基本上将其用作全文搜索。用户在文本框中输入一个字符串,它会像这样查询 VIEW:

SELECT * FROM vw_clients WHERE
col1 = "'%".$userInput."%'"
OR col2 = "'%".$userInput."%'"
OR col3 = "'%".$userInput."%'"
OR col4 = "'%".$userInput."%'"

我的结果正确返回,但有没有办法确定哪些列包含搜索词?通过 MySQL 还是 PHP?

4

4 回答 4

4

不是直接在 MySQL 中,但是有一些非常丑陋的 hack:

SELECT col1, (col1 LIKE '%$userinput%') AS found_in_col1,
     col2, (col2 LIKE '%$userinput%') AS found_in_col2, 
     etc...
etc...
WHERE ...

在 php 中,只需遍历结果集中的字段并进行strpos()检查即可。不管怎样……丑陋。

于 2012-12-13T18:54:32.407 回答
2
   SELECT 
      *,
      CONCAT_WS(',',
        IF(col1 = "'%".$userInput."%'",'col1',NULL),
        IF(col2 = "'%".$userInput."%'",'col2',NULL),
        IF(col3 = "'%".$userInput."%'",'col3',NULL),
        IF(col4 = "'%".$userInput."%'",'col4',NULL)) as colmatches
   FROM ....
于 2012-12-13T18:56:50.407 回答
0

还有一种更丑陋的方法:在选择查询中使用“case”或“if”:

SELECT CASE WHEN col1='%value%' THEN 'col1' WHEN col2='%value%' THEN 'col2' END as found_column
FROM ....
WHERE ....
于 2012-12-13T19:00:20.280 回答
0

像这样的东西:

SELECT IFNULL(v.col1 LIKE CONCAT('%','$userInput','%'),0) AS col1_match
     , IFNULL(v.col2 LIKE CONCAT('%','$userInput','%'),0) AS col2_match
     , IFNULL(v.col3 LIKE CONCAT('%','$userInput','%'),0) AS col3_match
     , IFNULL(v.col4 LIKE CONCAT('%','$userInput','%'),0) AS col4_match
     , v.*
  FROM vw_clients v
 WHERE v.col1 LIKE CONCAT('%','$userInput','%') = 1
    OR v.col2 LIKE CONCAT('%','$userInput','%') = 1
    OR v.col3 LIKE CONCAT('%','$userInput','%') = 1
    OR v.col4 LIKE CONCAT('%','$userInput','%') = 1

注意这个结构容易受到 SQL 注入的影响;它取决于$userInput不包含 SQL 构造。例如

$userInput = "foo')=1 OR '1' LIKE CONCAT('1";
于 2012-12-13T19:40:27.127 回答