我有这个查询来快速搜索我的数据库
$result = $apt->query("SELECT * FROM news where title like '%$searchfor%' order by item_id DESC limit 20");
我想在此搜索查询中包含“post”行的前100个字符以及标题行。有时我会在“post”行的前100个字符中找到人们可能搜索的一些字符。
任何想法? 谢谢
答案 0 :(得分:2)
您可以选择整个post
和title
并在PHP中截断它
<强> SQL 强>
SELECT post, title
FROM news WHERE title LIKE '%$searchfor%'
ORDER BY item_id DESC
LIMIT 20
<强> PHP 强>
function limit_words($words, $limit, $append = ' …') {
$limit = $limit+1;
$words = explode(' ', $words, $limit);
array_pop($words);
$words = implode(' ', $words) . $append;
return $words;
}
// this actually will give you 100 words
echo limit_words($result->post, 100);
// this will give you 100 characters
echo substr($result->post, 0, 100);
还有一种方法可以在SQL中直接执行,可以节省一些内存。
<强> SQL 强>
SELECT SUBSTRING(post, 0, 100) AS post, title
FROM news WHERE title LIKE '%$searchfor%'
ORDER BY item_id DESC
LIMIT 20
如果要同时搜索title
和post
字段,则需要将它们添加到WHERE子句中:
<强> SQL 强>
SELECT post, title
FROM news
WHERE title LIKE '%searchfor%' AND post LIKE '%searchfor%'
ORDER BY item_id DESC
LIMIT 20
### If you need to map search term in either post OR title ###
SELECT post, title
FROM news
WHERE title LIKE '%searchfor%' OR post LIKE '%searchfor%'
ORDER BY item_id DESC
LIMIT 20