try add GROUP BY activityid
like that :
where uf.userid = 7
GROUP BY activityid
Pregunta
I have one application where I have to show user's activities. I am facing one problem regarding duplicate entry/activities. First of all I have describe my schema:
CREATE TABLE `testDb`.`UserFriends` (
`Pk` INT NOT NULL AUTO_INCREMENT,
`Userid` INT NULL,
`Friendid` INT NULL,
PRIMARY KEY (`Pk`));
CREATE TABLE `testDb`.`UserActivities` (
`Pk` INT NOT NULL AUTO_INCREMENT,
`Userid` INT NULL,
`Friendid` INT NULL,
`ActivityType` TINYINT(1) NULL,
PRIMARY KEY (`Pk`));
Insert some dummy data into the tables.
INSERT INTO UserFriends(Userid, friendid )
values (7,105), (7,92)
INSERT INTO UserActivities(Userid, friendid )
values (92, 1054), (105,2014), (92,105)
I have one user (pk - 7) in UserFriends table with 2 friends (e.g. id no(s) 105 & 92). There is some activities which is done by user (eg.7) and its friends. User 92 has become friends with user 1054, user 105 has added user 2014 as a friend and user 92 and user 105 also become a friend. Now I have to show user 7 to his/her activities. I have create a query which is fined all activities of user itself as well as it's all friends. Here is the query :
select ua.pk activityid,
if(uf.Friendid = ua.userid, ua.userid, ua.Friendid) myfriend,
if(uf.Friendid = ua.Friendid, ua.Friendid, ua.Userid) friend_of_friend
from UserFriends uf
inner join UserActivities ua on uf.Friendid = if(uf.Friendid = ua.userid, ua.userid, ua.Friendid)
where uf.userid = 7
and I have got result as follows :
activityid, myfriend, friend_of_friend
1, 92, 1054
2, 105, 2014
3, 105, 92
3, 92, 105
Please check result carefully, there is a duplicate records come for activity id 3 due to join. User 7 has two friends (eg. 92, 105), so it comes twice. I want only one records. I don't know how to remove/eliminate this records. My original query has 6-7 table join and activity table has about 600000 records and userfriend table as around 200000 records. so I have to consider performance too. Please anyone can help to me to solve this problem. thanks.
Solución
try add GROUP BY activityid
like that :
where uf.userid = 7
GROUP BY activityid
Otros consejos
Can you check this query
select DISTINCT ua.pk activityid,
if(uf.Friendid = ua.userid, ua.userid, ua.Friendid) myfriend,
if(uf.Friendid = ua.Friendid, ua.Friendid, ua.Userid) friend_of_friend
from UserFriends uf
inner join UserActivities ua on uf.Friendid = if(uf.Friendid = ua.userid, ua.userid, ua.Friendid)
where uf.userid = 7
I have used a distinct keyword before ua.pk
.