查询联合,如果搜索结果小于10,则按日期从数据库顺序填写其他联合

时间:2011-11-06 15:58:24

标签: php mysql

我想进行mysql联合搜索。我的目的是:我的总结果必须是10.

  • 如果搜索结果大于10,则返回的数据全部来自搜索结果。
  • 如果搜索结果小于10,则前几个返回的数据来自搜索结果,然后按日期从数据库中获取剩余的结果。

为了更清楚:如果客户端搜索“今天”,我的数据库只返回包含“今天”的7个结果,然后从我的数据库ORDER BY日期添加另外3个结果。这样总的结果就是10个项目。

另一个目的:另外3个结果不是来自与搜索匹配的7个结果的重复。我认为UNIONUNION 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

1 个答案:

答案 0 :(得分:1)

如果您总是想要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)