Sql: joining two tables
I have two tables called mp_Blogs
and mp_BlogCategories
mp_blog
has columns and values
ItemID ModuleID
3 11
4 11
5 13
mp_BlogCategories
has column and values
CategoryID ModuleID
1 11
2 11
3 13
I need the output like this
ItemID CategoryID
3 1
4 2
5 3
I used this query
SELECT a.[ItemID],b.[CategoryID]
from [mp_Blogs] a
join [mp_BlogCategories] b
on a.ModuleID=b.ModuleID
But its coming in different way
ItemID CategoryID
3 1
4 1
3 2
4 2
5 3
I used groupby function also but output same as before,any mistake in query how to get my original output
SELECT a.开发者_JAVA技巧[ItemID],b.[CategoryID]
from [mp_Blogs] a
join [mp_BlogCategories] b
on a.ModuleID=b.ModuleID
group by b.CategoryID,a.ItemID
You query is performing properly but there is problem with data in you table as you can see the table contains 11 id two time thats y its giving the result like that. its better to check out the data in table.
From the Output it seems there is something wrong with the Data, not the Query.
After reading comments you are lacking for unique key in both the tables so i suggest you to add key in both the tables in order to achieve your result.
How it would be - tested in mysql working fine.
-- id column primary key in mp_blog table.
create table mp_blog(id smallint(5),ItemID smallint(5),
ModuleID smallint(5),constraint mp_blog_id primary key(id));
insert into mp_Blog values(1,3,11),(2,4,11),(3,5,13);
-- id column foreign key references to mp_blog primary key id.
create table mp_BlogCategories(id smallint(5),CategoryID smallint(5),
ModuleID smallint(5),constraint fk_mp_blogc foreign key(id) references mp_blog(id));
insert into mp_BlogCategories values(1,1,11),(2,2,11),(3,3,13);
-- finally what you are trying to achieve..
select b.itemid,bc.categoryid
from mp_blog b INNER JOIN mp_BlogCategories bc
on b.id=bc.id;
ItemID CategoryID
3 1
4 2
5 3
精彩评论