[英]Complex mysql query issue
Im currently working on a live search and ran into the following problem:我目前正在进行实时搜索并遇到以下问题:
The following query works but i would rather gather "topic" and "threadid" columns from table "bb1_threads" and only column "message" from table "bb1_posts"以下查询有效,但我宁愿从表“bb1_threads”中收集“topic”和“threadid”列,只从表“bb1_posts”中收集“message”列
SELECT posttopic AS topic, threadid FROM bb".$n."_posts WHERE message LIKE '%$search_string%' OR posttopic LIKE '%$search_string%' LIMIT 1
The following query also works but i cant search the field "message" from table bb1_posts this way:以下查询也有效,但我无法通过这种方式从表 bb1_posts 中搜索字段“消息”:
SELECT topic, threadid FROM bb".$n."_threads WHERE topic LIKE '%$search_string%' LIMIT 1
So what i would like to have and tried to build for hours is a query that:所以我想要并尝试构建几个小时的是一个查询:
If someone could post a ready to use query, i would really appreciate that: Merry Christmas :)如果有人可以发布现成的查询,我将不胜感激:圣诞快乐 :)
I need this code is exactly what you need:我需要这段代码正是你所需要的:
SELECT t.threadid, t.topic, p.message
FROM bb".$n."_threads t
LEFT JOIN bb".$n."_posts p ON t.threadid = p.threadid
WHERE t.topic LIKE '%$search_string%' OR p.message LIKE '%$search_string%'
ORDER BY (CASE
WHEN p.message LIKE '%$search_string%' THEN 1
ELSE 2
END) ASC
LIMIT 1
This query will select the threadid and topic columns from the bb1_threads table, and the message column from the bb1_posts table.此查询将从 bb1_threads 表中选择 threadid 和 topic 列,并从 bb1_posts 表中选择 message 列。 It will search for the $search_string in both the topic and message columns, and then sort the results by which column the search string was found in first (so the result with a match in the message column will come before the result with a match in the topic column).
它将在主题和消息列中搜索 $search_string,然后根据首先找到搜索字符串的列对结果进行排序(因此在消息列中匹配的结果将排在在中匹配的结果之前主题栏)。 Finally, it will return only the first result, using the LIMIT 1 clause.
最后,它将使用 LIMIT 1 子句仅返回第一个结果。
This may work.这可能有效。
search bb1_posts
by message
and assign 1
as search_rank
通过
message
搜索bb1_posts
并将1
指定为search_rank
search bb1_thread
by topic
and assign 2
as search_rank
按
topic
搜索bb1_thread
并将2
指定为search_rank
union results from both, order by search_rank
and pick the first row结合两者的结果,按
search_rank
排序并选择第一行
select threadid as threadid,
posttopic as topic,
1 as search_rank
from bb1_posts
where message like '%$search_string%'
union all
select threadid as threadid,
topic as topic,
2 as search_rank
from bb1_threads
where topic like '%$search_string%'
order by search_rank
limit 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.