我有一张这样的表:
// mytable
+----+---------+-------------------------------+
| id | title | content |
+----+---------+-------------------------------+
| 1 | hello | how are you? |
| 2 | you | it is content2 |
| 3 | what | hello is a word for greating |
| 4 | mouse | it is content4 |
+----+---------+-------------------------------+
好吧,我想优先考虑title
而不是content
。我的意思是,我希望显示title
列的所有结果(在第一个中),然后显示content
列的所有结果(在第二个中)。这也是我的问题:
select * from mytable where match(title, content) against($word);
这里有两个例子:
例1:
$word = 'you';
我想要这个输出:(专注于排序)
+----+---------+-------------------------------+
| id | title | content |
+----+---------+-------------------------------+
| 2 | you | it is content2 |
| 1 | hello | how are you? |
+----+---------+-------------------------------+
例2:
$word = 'hello';
我想要这个输出:(专注于排序)
+----+---------+-------------------------------+
| id | title | content |
+----+---------+-------------------------------+
| 1 | hello | how are you? |
| 3 | what | hello is a word for greating |
+----+---------+-------------------------------+
我再次强调,我希望title
列中的所有结果都来自content
列。有没有解决方案?
答案 0 :(得分:3)
您需要做的就是使用CASE和匹配字的条件顺序。这是一个让你前进的例子
SELECT title, content
FROM tablename
ORDER BY CASE
WHEN title LIKE '%you%' THEN 1
WHEN content LIKE '%you%' THEN 2
ELSE 3
END;
答案 1 :(得分:0)
针对2列运行2个单独的查询,并将它们与union组合成单个结果集:
select * from mytable where match(title) against($word);
union distinct
select * from mytable where match(content) against($word);
编辑:
如果你不喜欢联合方法,那么创建3个全文索引,onne on title,one on on content,and one one with the bining 2.然后使用以下方法:
SELECT title, content,
MATCH (title) AGAINST ($word) AS c1,
MATCH (content) AGAINST ($word) AS c2
FROM tablename
WHERE MATCH (title,content) AGAINST ($word)
ORDER BY IF(c1> 0,1,0)
组合索引将用于搜索,而各个索引将用于产生加权。但是,如果发现一个单词太多次,其权重可能会减少到0。
答案 2 :(得分:-1)
select * from mytable where match(title) against($word);
union
select * from mytable where match(content) against($word);