mysql - Returning most common linked ID for a user -


i have 3 tables. user_sticker holds sent stickers between users. when profile view screen loaded, need display common sticker has been given user.

user

  • id_user
  • name

sticker

  • id_sticker
  • name

user_sticker

  • id_user_sticker
  • id_sticker
  • id_user_from
  • id_user_to

so, if user_sticker holds info:

  • 1, 3, 254, 205
  • 2, 2, 362, 205
  • 3, 2, 519, 205
  • 4, 3, 945, 205
  • 5, 3, 199, 205

(which means users 254, 362, 519, 945, 199 sent stickers user 205). result has return both user 205 information (name) , common sticker id (in case #3) in same record.

ok, lets see

in principal, need use user_sticker table. so:

select * user_sticker 

then, match user table user_to

select * user_sticker join user u on us.id_user_to = u.id_user 

then, want name , stickers user want recieve

select us.id_sticker, u.name user_sticker join user u on us.id_user_to = u.id_user u.id_user = "yourwanteduser" 

now, pick first

select top 1 us.id_sticker, u.name user_sticker join user u on us.id_user_to = u.id_user u.id_user = "yourwanteduser" order (select count(*)           user_sticker us2           us2.id_user_to=u.id_user , us2.id_sticker=us.id_sticker) 

the order used search how many of stickers sent user

sorry bad english! hope help!


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -