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

2022-08-30 11:47:44

我的数据库中有三个表,它们是:

messages
topics
comments

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

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

mysql_query("SELECT * FROM messages 
WHERE content LIKE '%" . $keyword . "%' 
OR title LIKE '%" . $keyword ."%'");

我也想知道,一旦我从多个表获得结果,我怎么能知道什么表的结果是什么?

任何帮助将不胜感激!


答案 1
$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);

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


答案 2

您可能要查找的是 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%'

推荐