我想创建一个搜索功能,根据帖子的标题和帖子搜索帖子。我想知道是否有可能只使用mysql查询或者我需要使用2个查询然后使用php对结果进行排序。
我尝试过这样的事情,但它会返回重复的帖子:
SELECT post_tags.id, post_tags.tag_id, posts.id, tags.tag_name,
posts.title
FROM post_tags
JOIN tags ON (tags.tag_name LIKE '%something%' AND post_tags.tag_id = tags.id)
JOIN posts ON (posts.title LIKE '%something%' OR post_tags.post_id = posts.id);
我也听说过在mysql中使用LIKE
非常慢,因为没有索引。
因此,我的问题是,如果有这种情况,这种情况的最佳做法是什么?
- 编辑 -
我添加了使用2个查询来实现我想要的PHP代码
function search($query, $con = null){
$conn = (isset($con) ? $con : get_conn());
$logged_in_user_id = current_user.id;
$posts = Array();
$param = "%$query%";
if($stmt = $conn->prepare("SELECT posts.id, posts.title ...
FROM post_tags
JOIN tags ON post_tags.tag_id = tags.id
JOIN posts ON (post_tags.post_id = posts.id OR posts.title LIKE ?)
WHERE posts.title LIKE ? OR tags.tag_name LIKE ?;")){
$stmt->bind_param('sss', $param,$param, $param);
$stmt->execute();
$stmt->bind_result($id, $title ...);
while($stmt->fetch()){
if(!array_key_exists($id, $posts)){
$posts[$id] = new Post($id, $title ...);
}
}
}
return $posts;
}
答案 0 :(得分:0)
试试这段代码:
var t = {
"s": {
"2MqcJqtmNYDZlcbDZY3yjA==": "[{\"id\":\"global_mute\",\"expiration\":0}]",
"BrowserId": "\"TAMGVxD/wr9fL47xJZAciw==\"",
"SecretBundle": "{\"key\":\"2Eiw3rJZI9oErblie5mx+xXPjd+tj6t0hqQHC+EQ8Bc=\",\"encKey\":\"aGLPEm0dyq6W/gHN5cVONhdOR6lv2CGm4v4GLJ7LyoM=\",\"macKey\":\"2Eiw3rJZI9oErblie5mx+xXPjd+tj6t0hqQHC+EQ8Bc=\"}",
"Token1": "\"OG7aZ02ndonc1DGnfJ3bswG3na3Wr5OB7bwdgiwdd4Y=\"",
"Token2": "\"1@Sf53vRMCbVuLW0Q1diEg95TVBWRMDOjG7mqI8XIfOjr+hMiTwyqjKM72NKgxZJBGtfkETDmqfCgVLQ==\"",
"Xz+yNzfxx8EbdaUFWVxmjg==": "false",
"debugCursor": "191",
"ghI8QhVRLDvFWJDpV7Cx5g==": "false",
"logout-token": "\"1@MZ9F8QbLN9iGKNeZGbCJdzKwPHq7L5sJrpO6RtiG35rdu5TVLu/+z3gGNmbYG59h1Grzfwcnz44uLVencqRdP044ZpWuT02+ltcEM+9aCURZQkBG+oRyeWNAHcInXMWCpWysPF5d/ISLnbfeV1NVoA==\"",
"remember-me": "true",
"storage_test": "storage_test"
},
"c": ""
}
答案 1 :(得分:0)
你可以试试这个:
SELECT
p.id,
p.title,
GROUP_CONCAT(t.tag_name) as `tags`,
FROM posts p
JOIN post_tags p1
ON pt.post_id = posts.id
JOIN tags t
ON pt.tag_id = tags.id
WHERE p.title LIKE '%something%' OR t.tag_name LIKE '%something%'
GROUP BY p.id
ORDER BY p.title