简体   繁体   中英

How to use INNER JOIN in this example

I am learning about mysql joins and I have a simple question:

I have one database and two tables blogs and tags

blogs:

MariaDB [cvv]> describe blogs;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| slug         | varchar(255) | YES  |     | NULL    |                |
| title        | varchar(255) | YES  |     | NULL    |                |
| content      | text         | YES  |     | NULL    |                |
| created_at   | datetime     | YES  |     | NULL    |                |
| updated_at   | datetime     | YES  |     | NULL    |                |
| user_id      | int(11)      | YES  |     | NULL    |                |
| is_published | tinyint(1)   | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

tags:

MariaDB [cvv]> describe tags;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| id      | int(11)     | NO   | PRI | NULL    | auto_increment |
| name    | varchar(15) | YES  |     | NULL    |                |
| blog_id | int(11)     | YES  | MUL | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

Basically I am trying to fetch a blog and its tags using:

SELECT  blogs.id, blogs.title tags.name as tags FROM blogs INNER JOIN tags ON blogs.id = tags.blog_id  

But this query does not return more than 1 tag at a time.

for example I created a blog id, title .. and in the tag I created two tags and they both have blog_id of 1 so, I should be getting the blog id, title an TWO tags, but I only get one.

Also, I have made a reference in tags table with constraint name blog_id referencing to the id of blog ie: blog.id

This query:

SELECT b.id, b.title, t.name as tags
FROM blogs b INNER JOIN 
     tags t
     ON b.id = t.blog_id ;

Should return multiple rows, with one blog/tag pair per row.

If you want all tags for a blog on the same row, then you need to aggregate the results:

SELECT b.id, b.title, GROUP_CONCAT(t.name) as tags
FROM blogs b INNER JOIN 
     tags t
     ON b.id = t.blog_id
GROUP BY b.id, b.title;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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