我想进行 mysql 联合搜索。我的目的是:我返回的总结果必须是 10。
- 如果搜索结果超过10条,返回的数据全部来自搜索结果。
- 如果搜索结果少于10条,则前几条返回数据来自搜索结果,然后按日期顺序从数据库中获取剩余结果。
为了更清楚:如果客户搜索“今天”,我的数据库只返回 7 个包含“今天”的结果,然后从我的数据库中按日期添加另外 3 个结果。所以总的结果是10项。
另一个目的:另外 3 个结果不是与搜索匹配的 7 个结果的重复。我认为 UNION
或 UNION DISTINCT
可以完成这项工作,对吗?
那么,我该如何进行这样的查询呢?
PS:我的代码会固定结果顺序,但我需要第一个select
总是在第二个select
(SELECT * FROM table WHERE title like %$searchword% limit 0,10 ORDER BY date)
UNION
(SELECT * FROM table limit 0,10 ORDER BY date)
limit 0,10 ORDER BY date
最佳答案
如果您总是想要 10 个结果:
SELECT
IF(m.id,1,0) AS has_match,
t.*
FROM
`table` t
LEFT JOIN `table` m ON m.id = t.id AND m.title LIKE '%$searchword%'
GROUP BY t.id
ORDER BY has_match DESC, date
LIMIT 10
测试:
mysql> select * from `table`;
+----+------------------------+---------------------+
| id | title | date |
+----+------------------------+---------------------+
| 1 | test 1 | 2011-11-06 10:27:08 |
| 2 | test 2 match | 2011-11-06 10:27:14 |
| 3 | 3 match this too | 2011-11-06 10:27:23 |
| 4 | title does NOT | 2011-11-06 10:27:44 |
| 5 | Another matching title | 2011-11-06 10:27:55 |
| 6 | this does not either | 2011-11-06 10:29:22 |
| 7 | Do not put this first | 2011-11-06 10:29:37 |
| 8 | Is this number 8? | 2011-11-06 10:29:57 |
| 9 | The 9th is a match | 2011-11-06 10:30:07 |
| 10 | 10th does not | 2011-11-06 10:30:20 |
| 11 | 11th IS a match too! | 2011-11-06 10:30:37 |
| 12 | 12th gets ignored? | 2011-11-06 10:30:49 |
+----+------------------------+---------------------+
12 rows in set (0.00 sec)
mysql> SELECT IF(m.id,1,0) AS has_match, t.* FROM `table` t LEFT JOIN `table` m ON m.id = t.id AND m.title LIKE '%match%' GROUP BY t.id ORDER BY has_match DESC, date LIMIT 10;
+-----------+----+------------------------+---------------------+
| has_match | id | title | date |
+-----------+----+------------------------+---------------------+
| 1 | 2 | test 2 match | 2011-11-06 10:27:14 |
| 1 | 3 | 3 match this too | 2011-11-06 10:27:23 |
| 1 | 5 | Another matching title | 2011-11-06 10:27:55 |
| 1 | 9 | The 9th is a match | 2011-11-06 10:30:07 |
| 1 | 11 | 11th IS a match too! | 2011-11-06 10:30:37 |
| 0 | 1 | test 1 | 2011-11-06 10:27:08 |
| 0 | 4 | title does NOT | 2011-11-06 10:27:44 |
| 0 | 6 | this does not either | 2011-11-06 10:29:22 |
| 0 | 7 | Do not put this first | 2011-11-06 10:29:37 |
| 0 | 8 | Is this number 8? | 2011-11-06 10:29:57 |
+-----------+----+------------------------+---------------------+
10 rows in set (0.00 sec)
关于php - 查询并集,如果查询结果小于10条,按日期顺序从数据库中取其他的补齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8028257/