以如下形式提供mysql查询:
SELECT *
FROM table
WHERE field1 LIKE '%foo%'
OR field2 LIKE '%bar%'
OR field3 LIKE '%foobar%'
哪种是标记“匹配字段”的最佳方法?
例如:
+----+--------+--------+----------+
| ID | field1 | field2 | field3 |
+----+--------+--------+----------+
| 01 | foo | xxx | xxx |
+----+--------+--------+----------+
| 02 | xxx |12bar21 |xxfoobarxx|
+----+--------+--------+----------+
| 03 | f2o | bar | yxz |
+----+--------+--------+----------+
这里每条记录都会匹配-现在我想知道每条记录的哪个字段匹配。 (因此,对于ID 01,它是field1,对于ID 02,它是field2,field3,对于ID 03,它是field2)
谢谢
答案 0 :(得分:1)
您可以使用条件将标记添加到您的选择中,例如:
SELECT *,
IF(field1 LIKE '%foo%', 1, 0) AS field1_matches,
IF(field2 LIKE '%bar%', 1, 0) AS field2_matches,
IF(field3 LIKE '%foobar%', 1, 0) AS field3_matches
FROM TABLE
WHERE field1 LIKE '%foo%'
OR field2 LIKE '%bar%'
OR field3 LIKE '%foobar%'
如果您需要在单个字段中将结果作为逗号分隔的列表,则可以使用CONCAT_WS
将结果连接起来,并在条件不匹配时在条件内返回NULL
:
SELECT *,
CONCAT_WS(',',
IF(field1 LIKE '%foo%', 'field1', NULL),
IF(field2 LIKE '%bar%', 'field2', NULL),
IF(field3 LIKE '%foobar%', 'field3', NULL)
) AS matches
FROM TABLE
WHERE field1 LIKE '%foo%'
OR field2 LIKE '%bar%'
OR field3 LIKE '%foobar%'
答案 1 :(得分:0)
$ ./bin/cgmasses_read <dat/cgmasses.txt
10 objects read:
1.37 1.37 713.54
3.00 3.00 189.55
1.05 1.05 276.15
2.57 2.57 238.94
2.17 2.17 189.03
6.73 6.73 263.26
3.26 3.26 795.61
9.41 9.41 283.92
1.60 1.60 279.72
1.70 1.70 719.12
表达式如何:
CASE
如果您只想匹配子字符串,则使用此:
SELECT
CASE WHEN field1 REGEXP '[[:<:]]foo[[:>:]]|[[:<:]]bar[[:>:]]|[[:<:]]foobar[[:>:]]'
THEN 'field1' ELSE '' END AS field1match,
CASE WHEN field2 REGEXP '[[:<:]]foo[[:>:]]|[[:<:]]bar[[:>:]]|[[:<:]]foobar[[:>:]]'
THEN 'field2' ELSE '' END AS field2match,
CASE WHEN field3 REGEXP '[[:<:]]foo[[:>:]]|[[:<:]]bar[[:>:]]|[[:<:]]foobar[[:>:]]'
THEN 'field3' ELSE '' END AS field3match
FROM yourTable
答案 2 :(得分:0)
使用 CONCAT
和CASE
您正是在寻找以下结果,但我知道您希望用逗号或其他任何符号分隔字段,因此,我现在无法访问mysql
,因此我认为您可以自己进行管理>
SELECT *,
CONCAT(CASE WHEN field1 LIKE '%foo%' THEN 'field1' ELSE NULL END,
CASE WHEN field2 LIKE '%bar%' THEN 'field2' ELSE NULL END,
CASE WHEN field3 LIKE '%foobar%' THEN 'field3' ELSE NULL END) AS macthed_column
FROM youtable
WHERE field1 LIKE '%foo%'
OR field2 LIKE '%bar%'
OR field3 LIKE '%foobar%'
输出:
ID field1 field2 field3 macthed_column
1 foo xxx xxx field1
2 xxx 12bar21 xxfoobarxx field2field3
3 f2o bar yxz field2