PHP mysql使用关键字搜索多个表

Эџa*_*мaи 28 php mysql full-text-search

我的数据库中有三个表:

messages
topics
comments
Run Code Online (Sandbox Code Playgroud)

这些表中的每一个都有两个名为"content"和"title"的字段.我希望能够在我的sql语句中使用'Like'来查看'messages.content','messages.title','topics.content','topics.title','comments.content'和'comments.标题'使用关键字.

到目前为止,我的查询只能从一个表中查找结果:

mysql_query("SELECT * FROM messages 
WHERE content LIKE '%" . $keyword . "%' 
OR title LIKE '%" . $keyword ."%'");
Run Code Online (Sandbox Code Playgroud)

我也想知道,一旦我从多个表中得到结果,我怎么能从哪个表中判断出结果是什么?

任何帮助将不胜感激!

MD *_*med 86

$query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" . 
           $keyword . "%' OR title LIKE '%" . $keyword ."%') 
           UNION
           (SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" . 
           $keyword . "%' OR title LIKE '%" . $keyword ."%') 
           UNION
           (SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" . 
           $keyword . "%' OR title LIKE '%" . $keyword ."%')";

mysql_query($query);
Run Code Online (Sandbox Code Playgroud)

因此,您将从所有三个表中获得结果,并且您可以通过查看其type值来确定哪个行来自哪个表.


eva*_*van 7

您可能正在寻找的是UNION命令:

SELECT id, 'messages' as 'table' FROM messages 
WHERE content LIKE '%keyword%' 
OR title LIKE '%keyword%'
UNION
SELECT id, 'topics' as 'table' FROM topics
WHERE content LIKE '%keyword%' 
OR title LIKE '%keyword%'
UNION
SELECT id, 'comments' as 'table' FROM comments
WHERE content LIKE '%keyword%' 
OR title LIKE '%keyword%'
Run Code Online (Sandbox Code Playgroud)