1

我正在创建一个引擎来使用 MySQL 在多个字段中查找结果,例如:

SELECT table1.*, table2.* FROM table1
JOIN table2
ON table1.id = table2.tid
WHERE 
(table1.field1 LIKE 'keyword%' OR table1.field2 LIKE 'keyword%')
AND
(table2.field1 LIKE 'keyword%' OR table2.field2 LIKE 'keyword%')
ORDER BY table1.id ASC;

但是现在我需要知道哪个字段与关键字匹配......我该怎么做?

顺便说一句,我正在使用 PHP。

4

4 回答 4

2

未经证实:

SELECT table1.*, 
       table2.*, 
       case (table2.field1 LIKE 'keyword%' and table1.field1 LIKE 'keyword%')
           when 1 
           then 'f1' 
           else 'f2' 
       end as field
FROM table1
...
于 2012-04-13T16:11:45.413 回答
1

你可以做

SELECT table1.*, table2.*, 'table1' as `target` as FROM table1
JOIN table2
ON table1.id = table2.tid
WHERE 
(table1.field1 LIKE 'keyword%' OR table1.field2 LIKE 'keyword%')
UNION ALL 
SELECT table1.*, table2.*,'table2' as target FROM table1
JOIN table2
ON table1.id = table2.tid
WHERE 
(table2.field1 LIKE 'keyword%' OR table2.field2 LIKE 'keyword%')

然后target在检索结果时检查是 table1 还是 table2

于 2012-04-13T16:10:24.577 回答
1

您可以为您的条件添加列

SELECT table1.*, table2.*, 
table1.field1 LIKE 'keyword%' AS Table1Field1Match, 
table1.field2 LIKE 'keyword%' AS Table1Field2Match,
table2.field1 LIKE 'keyword%' AS Table2Field1Match, 
table2.field2 LIKE 'keyword%' AS Table2Field2Match
FROM table1
JOIN table2
ON table1.id = table2.tid
WHERE 
(table1.field1 LIKE 'keyword%' OR table1.field2 LIKE 'keyword%')
AND
(table2.field1 LIKE 'keyword%' OR table2.field2 LIKE 'keyword%')
ORDER BY table1.id ASC;
于 2012-04-13T16:11:04.867 回答
0

在您的循环中,您可以这样做:

Table X
Field1      Field2
-------------------
boat        caca
hello       boat

$Keyword = 'boat';
while($Res = blabla){
    if(strpos($Res['Field1'], $Keyword) !== false){
        echo 'String found in Field 1<br />';
    }

    if(strpos($Res['Field2'], $Keyword) !== false){
        echo 'String found in Field 2<br />';
    }
}

// Will output
String found in Field 1<br />
String found in Field 2<br />
于 2012-04-13T16:10:46.230 回答