PHP mysql 使用关键字搜索多个表 [英] PHP mysql search multiple tables using a keyword

查看:32
本文介绍了PHP mysql 使用关键字搜索多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have three tables in my database which are:

messages
topics
comments

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

Each of these tables has two fields called 'content' and 'title'. I want to be able to use 'Like' in my sql statement to look at 'messages.content', 'messages.title', 'topics.content', 'topics.title', 'comments.content' and 'comments.title' using a keyword.

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

So far, my query is able to find results from only one table:

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

我也想知道,一旦我从多个表中得到结果,我怎么知道结果是来自哪个表?

I am also wondering, once I get the results from multiple tables, how can I tell what result is from what table?

任何帮助将不胜感激!

推荐答案

$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 值来确定哪一行来自哪个表.

So, you are getting result from all of the three tables, and you can identify which row came from which table by looking at its type value.

这篇关于PHP mysql 使用关键字搜索多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆