简体   繁体   English

如何在单个查询中查询3个表?

[英]How to query 3 tables in a single query?

I'm really sorry for the first post as i didn't explain everything. 对于第一篇文章,我真的很抱歉,因为我没有解释所有事情。

Basically i have 3 tables, One for posts, One for Categories, & Another to link categories with posts. 基本上我有3个表,一个表用于帖子,一个表用于类别,另一个用于将类别与帖子链接。

I want in a single MySQL query to select posts that are under a specific category. 我希望在一个MySQL查询中选择特定类别下的帖子。

posts(id,title,body)
---------------------
125,Some title,Blah blah


categories(id,name)
---------------------
1,politic
2,entertainment

linker(categoryid,postid)
---------------------
2,125

I want in single query to fetch posts in the entertainment category by example, what to do? 我想在单个查询中以示例方式获取娱乐类别中的帖子,怎么办?

Thanks 谢谢

select 
     p.*
from 
     posts p
     inner join linker l on l.postid = p.id
     inner join categories c on c.categoryid = l.categoryid
where 
     c.name = 'entertainment'

It's the same exact thing, you just have to join 3 tables intead of 2 : 这是完全相同的事情,您只需要将intead中的3个表联接在一起:

SELECT P.id post_id,
       P.title,
       P.body,
       C.id category_id,
       C.name
FROM posts P
INNER JOIN linker L
    ON P.id = L.postid
INNER JOIN categories C
    ON L.categoryid = C.id
WHERE C.name = 'Category'

Don't be afraid to do your own tests. 不要害怕做自己的测试。 If you understand how to join two tables, you should understand how to join three, four and more. 如果您了解如何联接两个表,则应了解如何联接三个,四个及更多。

The following SQL statement should provide you with a basis for what you are trying to do. 以下SQL语句应为您尝试做的事情提供基础。

select p.*
from posts p
inner join linker l
on l.postid = p.id
inner join categories c
on l.categoryid = c.id
where c.name = 'entertainment'

If a post belongs to 2 categories, you can still use pinkfloydx33's query with DISTINCT in the select statement: 如果帖子属于2个类别,您仍然可以在select语句中使用带DISTINCT的pinkfloydx33的查询:

select 
     DISTINCT p.*
from 
     posts p
     inner join linker l on l.postid = p.id
     inner join categories c on c.categoryid = l.categoryid
where 
     c.name = 'entertainment'

The result set will show only one record. 结果集将仅显示一条记录。

If you are specifying only one category in the WHERE clause, then the result will be a single row for each post ID. 如果仅在WHERE子句中指定一个类别,则结果将是每个帖子ID的一行。

Either way you can use DISTINCT or GROUP BY when the result could be more than one row per ID, but in that case i prefer the second one (GROUP BY). 无论哪种方式,当每个ID的结果可能超过一行时,都可以使用DISTINCT或GROUP BY,但是在那种情况下,我更喜欢第二行(GROUP BY)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM