Need help to retrieve data from three MySQL tables -
i have 3 tables named "users","user_hobbies" , "hobbies". below sample tables values;
below users table fields id, name , age
╔════╦══════╦═════╗ ║ id ║ name ║ age ║ ╠════╬══════╬═════╣ ║ 1 ║ abc ║ 23 ║ ║ 2 ║ xyz ║ 24 ║ ║ 3 ║ pqr ║ 21 ║ ╚════╩══════╩═════╝
and below user_hobbies table fields id, user_id , hobby_id
╔════╦═════════╦══════════╗ ║ id ║ user_id ║ hobby_id ║ ╠════╬═════════╬══════════╣ ║ 1 ║ 1 ║ 1 ║ ║ 2 ║ 1 ║ 2 ║ ║ 3 ║ 1 ║ 3 ║ ║ 4 ║ 2 ║ 4 ║ ║ 5 ║ 2 ║ 3 ║ ║ 6 ║ 2 ║ 5 ║ ║ 7 ║ 3 ║ 2 ║ ║ 8 ║ 4 ║ 6 ║ ╚════╩═════════╩══════════╝
. below hobbies table fields id , desc
╔════╦═══════════╗ ║ id ║ desc ║ ╠════╬═══════════╣ ║ 1 ║ music ║ ║ 2 ║ chatting ║ ║ 3 ║ cricket ║ ║ 4 ║ badminton ║ ║ 5 ║ chess ║ ║ 6 ║ cooking ║ ╚════╩═══════════╝
. actual requirement need query retrieve name, age, hobby_id , desc (see example below)
╔══════╦═════╦══════════╦═════════════════════════╗ ║ name ║ age ║ hobbyid ║ desc ║ ╠══════╬═════╬══════════╬═════════════════════════╣ ║ abc ║ 23 ║ 1,2,3 ║ music,chatting,cricket ║ ║ pqr ║ 21 ║ 2 ║ chatting ║ ║ xyz ║ 24 ║ 4,3,5 ║ badminton,cricket,chess ║ ╚══════╩═════╩══════════╩═════════════════════════╝
you need join tables first , use aggregate function called group_concat()
.
select a.name, a.age, group_concat(c.id) hobbyids, group_concat(c.desc) desclist users inner join user_hobbies b on a.id = b.user_id inner join hobbies c on b.hobby_id = c.id group a.name, a.age
to further gain more knowledge joins, kindly visit link below:
output
╔══════╦═════╦══════════╦═════════════════════════╗ ║ name ║ age ║ hobbyids ║ desclist ║ ╠══════╬═════╬══════════╬═════════════════════════╣ ║ abc ║ 23 ║ 1,2,3 ║ music,chatting,cricket ║ ║ pqr ║ 21 ║ 2 ║ chatting ║ ║ xyz ║ 24 ║ 4,3,5 ║ badminton,cricket,chess ║ ╚══════╩═════╩══════════╩═════════════════════════╝