MYSQL多表联合查询的问题

WBOY
Release: 2016-06-06 20:45:28
Original
1493 people have browsed it

总共有三个表

post表:id,title,content
terms表:id,name
rela表:postid,termid

post表保存文章内容(文章ID、文章标题、文章内容),terms表保存分类内容(分类ID、分类名称),rela表保存的是文章分类信息,也就是文章ID对应的分类ID。

单纯匹配post表的title和content我知道是这样

<code>query( 
        "
        SELECT id, title
        FROM post
        WHERE (
            `title` LIKE  '%关键词%'
            OR  `content` LIKE  '%关键词%'
        )
        LIMIT 0 , 30
        "
    );
</code>
Copy after login
Copy after login

现在也要匹配相应的terms表的name,请问怎么写呢?

回复内容:

总共有三个表

post表:id,title,content
terms表:id,name
rela表:postid,termid

post表保存文章内容(文章ID、文章标题、文章内容),terms表保存分类内容(分类ID、分类名称),rela表保存的是文章分类信息,也就是文章ID对应的分类ID。

单纯匹配post表的title和content我知道是这样

<code>query( 
        "
        SELECT id, title
        FROM post
        WHERE (
            `title` LIKE  '%关键词%'
            OR  `content` LIKE  '%关键词%'
        )
        LIMIT 0 , 30
        "
    );
</code>
Copy after login
Copy after login

现在也要匹配相应的terms表的name,请问怎么写呢?

<code>select post.id, post.title from rela left join post on rela.postid = post.id left join terms on rela.termid = terms.id where post.title like '%关键词%' or post.content like '%关键词%' or terms.name like '%关键词%'
</code>
Copy after login

联合查询是 Mysql 比较基础的操作,题主应该花点时间掌握这个基础知识点。:)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template