简体   繁体   English

MySQL:联接三个表

[英]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: 这类作品有两个问题:

  1. Since posts can have multiple categories (ie multiple entries in categories per post_id ), I'm getting duplicates. 由于帖子可以有多个类别(即中多个条目categoriespost_id ),我得到重复。 I'd like to get rid of the duplicates but acknowledge if a post is in multiple categories. 我想删除重复项,但要确认帖子是否属于多个类别。
  2. I don't know how to go the step further and get the cat_name other than doing another query. 除了执行其他查询外,我不知道该如何进一步获取cat_name This seems a bit wasteful though. 不过,这似乎有点浪费。 Is there a way to do it in one query? 有没有办法在一个查询中做到这一点?

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.

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