这是我的问题:
SELECT ID, Name, Description
FROM MyTable
WHERE NAME LIKE :search OR Description LIKE '%search%'
OR Status LIKE '%search%'
OR ... Many Other Columns LIKE '%search%
当我获取数据时,我将其显示给他们搜索的用户。现在我只显示ID, Name & Description
。我还想显示哪个列与搜索字符串匹配。如果它匹配Status
我想显示行的状态,如果它与任何其他列匹配,我想显示它匹配的那列的值。
如果匹配多列,则无关紧要。我只需要第一列。
如果不选择所有栏目,这是否可行?然后在每个上运行PHP搜索以找出哪一个匹配?可以在MySQL中完成吗?
我希望尽可能快地制作它,因为我的搜索速度越来越慢,列数越来越多我添加到搜索中的更多表格,并且不希望此功能增加大量开销。
答案 0 :(得分:1)
你可以这样做有点混乱: -
SELECT ID,
Name,
Description,
CASE
WHEN NAME LIKE :search THEN 'NAME'
WHEN Description LIKE :search THEN 'Description'
WHEN Status LIKE :search THEN 'Status'
... Many Other Columns LIKE :search
ELSE 'Unknown Column'
END AS MatchingColumn
FROM MyTable
WHERE NAME LIKE :search OR Description LIKE :search OR Status LIKE :search OR
... Many Other Columns LIKE :search
缺点是您正在重复(相当耗时)检查。不确定MySQL是否设法优化这些,但如果没有,它不会让我感到惊讶。
替代方案可能是查询的UNION,每个条件一个。然后使用它作为子查询从中选择最大值。
使用UNION会给你这样的东西。它确实有一个好处,即每个UNIONed查询都可以使用索引(当你查看不同的列ORed一起得到匹配时,你当前的查询可以,假设LIKE没有使用前导通配符。< / p>
SELECT ID, Name, Description, MAX(MatchingColumn)
FROM
(
SELECT ID, Name, Description, 'NAME' AS MatchingColumn
FROM MyTable
WHERE NAME LIKE :search
UNION
SELECT ID, Name, Description, 'Description' AS MatchingColumn
FROM MyTable
WHERE Description LIKE :search
UNION
SELECT ID, Name, Description, 'Status' AS MatchingColumn
FROM MyTable
WHERE Status LIKE :search OR
) sub0
GROUP BY ID, Name, Description
答案 1 :(得分:1)
考虑以下内容......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, a INT NOT NULL, b INT NOT NULL, c INT NOT NULL);
INSERT INTO my_table (a,b,c) VALUES
(101,102,103),
(102,103,104),
(103,104,105),
(104,105,106),
(105,106,107);
SELECT * FROM my_table;
+----+-----+-----+-----+
| id | a | b | c |
+----+-----+-----+-----+
| 1 | 101 | 102 | 103 |
| 2 | 102 | 103 | 104 |
| 3 | 103 | 104 | 105 |
| 4 | 104 | 105 | 106 |
| 5 | 105 | 106 | 107 |
+----+-----+-----+-----+
SELECT id
, CASE WHEN a LIKE '%04%' THEN 'a' WHEN b LIKE '%04%' THEN 'b' WHEN c LIKE '%04%' THEN 'c' END col
, CASE WHEN a LIKE '%04%' THEN a WHEN b LIKE '%04%' THEN b WHEN c LIKE '%04%' THEN c END val
FROM my_table;
+----+------+------+
| id | col | val |
+----+------+------+
| 1 | NULL | NULL |
| 2 | c | 104 |
| 3 | b | 104 |
| 4 | a | 104 |
| 5 | NULL | NULL |
+----+------+------+