MySQL获取与WHERE子句匹配的列名

时间:2012-12-13 18:51:20

标签: php mysql

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

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

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

4 个答案:

答案 0 :(得分:4)

不是直接在MySQL中,但有一些丑陋的黑客攻击:

SELECT col1, (col1 LIKE '%$userinput%') AS found_in_col1,
     col2, (col2 LIKE '%$userinput%') AS found_in_col2, 
     etc...
etc...
WHERE ...
在PHP中,它是循环结果集中的字段并进行strpos()检查的问题。无论哪种方式......丑陋。

答案 1 :(得分: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 ....

答案 2 :(得分:1)

还有一个丑陋的方法:在select query中使用“case”或“if”:

SELECT CASE WHEN col1='%value%' THEN 'col1' WHEN col2='%value%' THEN 'col2' END as found_column
FROM ....
WHERE ....

答案 3 :(得分: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

N.B。此构造易受SQL注入攻击;它取决于$userInput不包含SQL结构。例如

$userInput = "foo')=1 OR '1' LIKE CONCAT('1";