[英]MySQL: Join three tables
I'm new to this so please forgive the basic question. 我对此并不陌生,因此请原谅基本问题。 I'm just having a hard time conceptualizing how this would work.
我只是很难理解这将如何工作。
Say I have three tables in my database with these relevant columns: 假设我的数据库中有三个表,其中包含以下相关列:
POSTS - post_id, post_title, post_date
CATEGORIES - post_id, cat_id
CATEGORY NAMES - cat_id, cat_name
Now, I'm trying to display a list of all posts sorted by the post_date. 现在,我试图显示按post_date排序的所有帖子的列表。 In this list, I'd like to list the category.
在此列表中,我想列出类别。
I've gotten as far as this: 我已经做到了这一点:
SELECT *
FROM posts
LEFT JOIN categories ON posts.post_id = categories.post_id
ORDER BY post_date ASC
This sort of works but has two problems: 这类作品有两个问题:
categories
per post_id
), I'm getting duplicates. categories
每post_id
),我得到重复。 I'd like to get rid of the duplicates but acknowledge if a post is in multiple categories. cat_name
other than doing another query. cat_name
。 This seems a bit wasteful though. Again, sorry for the basic nature of this. 再次,为此感到遗憾。 I've been reading tutorials for a long time but I can't seem to wrap my head around this.
我已经阅读了很长时间的教程,但是我似乎无法将其束之高阁。 Any direction is appreciated.
任何方向表示赞赏。
One row per post, eh? 每个帖子一行,是吗? How about we give you the category names comma-separated?
我们给您以逗号分隔的类别名称怎么样?
SELECT p.post_title, p.post_date,
GROUP_CONCAT(c.cat_name SEPARATOR ', ') AS categories
FROM posts AS p
LEFT JOIN categories AS pc ON p.post_id = pc.post_id
LEFT JOIN category_names AS c ON pc.cat_id = c.cat_id
GROUP BY p.post_title, p.post_date
ORDER BY p.post_date ASC, p.post_title
The two consecutive joins pick up the category name, and the GROUP_CONCAT
aggregates multiple category names into a comma-separated list. 两个连续的联接选择类别名称,然后
GROUP_CONCAT
将多个类别名称聚合到一个逗号分隔的列表中。 For GROUP_CONCAT
to work we also need GROUP BY
. 为了使
GROUP_CONCAT
工作,我们还需要GROUP BY
。
use this format: 使用以下格式:
SELECT t1.name
,t1.age
,GROUP_CONCAT(t2.job_name SEPARATOR',')typeofjob
FROM t_one AS t1
JOIN t_three AS t3 ON t3.user_id = t1.user_id
JOIN t_two AS t2 ON t2.job_id = t3.job_id
GROUP BY t1.user_id;
output: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.