Home > Backend Development > PHP Tutorial > 多对多的查询,三表查询,求mysql语句

多对多的查询,三表查询,求mysql语句

WBOY
Release: 2016-06-23 13:40:08
Original
1116 people have browsed it

普通应用:文章和标签的数据表,然后查询某个标签,如“技术”,能够查询出所有技术类的文章。

文章表article: 

aid, title,content-----------------------------------------1   Qt助力跨平台应用开发,势不可挡2   Qt助力跨平台应用开发,势不可挡3   Qt助力跨平台应用开发,势不可挡4   Qt助力跨平台应用开发,势不可挡
Copy after login


标签表tags:
tid,tname--------------------------------1   生活2   技术3   科技4   娱乐
Copy after login


文章标签关系表art_tags:
aid,tid----------------------------1 11 21 32 12 32 43 13 23 44 14 2
Copy after login


然后根据标签搜索关键词“技术”,应该显示1、3、4这三篇文章


回复讨论(解决方案)

select a.* from article as a left join art_tags at on at.aid=a.aid where at.tid=2

select a.* from article as a left join art_tags at on at.aid=a.aid where at.tid=2



at.tid=2 ? 这个没法事先得知的啊。用户输入的是汉字“技术”

select * from article where aid in(select aid from art_tags where tid in(select tid from tags where tname='技术'));
Copy after login

select a.* from article a left join art_tags b on a.aid=b.aid left join tags c on c.tid=b.tid where b.tname='技术'
Copy after login
 

谢谢!
原来where也可以这么写

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