问题
so..I am learning many to many relationship in mysql.
I created the following tables.
create table post(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
title varchar(40),
content text,
created int(11) default 0
);
create table category(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(35)
);
create table author(
id int not null primary key auto_increment,
name varchar(20)
);
create table postcategory(
id int not null primary key auto_increment,
post_id int,
category_id int,
foreign key(category_id) references category(id)
on delete no action,
foreign key(post_id) references post(id)
on delete no action
);
These are rows I Inserted
insert into author(name) values('James');
insert into author(name) values('Moon');
insert into author(name) values('Min');
insert into category(name) values('C#');
insert into category(name) values('Art');
insert into category(name) values('PHP');
insert into category(name) values('Programming');
insert into post(title) values ('Introduction to C#');
insert into post(title) values ('Modern Art');
insert into post(title) values ('PHP Classes');
insert into post(title) values ('Classes in C#');
insert into post(title) values ('Polymorphism in C#');
insert into post(title) values ('Classic Art');
insert into post(title) values ('OOP in PHP');
insert into postcategory(post_id,category_id) values(1,1);
insert into postcategory(post_id,category_id) values(4,1);
insert into postcategory(post_id,category_id) values(5,1);
insert into postcategory(post_id,category_id) values(2,2);
insert into postcategory(post_id,category_id) values(2,6);
insert into postcategory(post_id,category_id) values(3,3);
insert into postcategory(post_id,category_id) values(3,7);
insert into postcategory(post_id,category_id) values(1,4);
insert into postcategory(post_id,category_id) values(4,4);
insert into postcategory(post_id,category_id) values(5,4);
insert into postcategory(post_id,category_id) values(3,4);
insert into postcategory(post_id,category_id) values(7,4);
basically I have post, author, category, and a joining table named postcategory.
so far, I can think of two queries with postcategory table.
- Query all the posts in C# category
- Query all the categories with post id #1
Are there any other queries (I am sure there are..) that I can use with postcategory table?
I'm Just trying to learn many to many relationship usage cases.
回答1:
How about list the categories, and how many posts in each category, sorted from the category with the most posts to the category with the least.
回答2:
You can query if any posts belongs to more then one category.
E.g find posts which belong to C# and Programming.
来源:https://stackoverflow.com/questions/5100093/what-other-queries-can-i-do-with-this-many-to-many-joining-table