I have two tables.
Table Emp
id name
1 Ajay
2 Amol
3 Sanjay
4 Vijay
Table Sports
Sport_name Played by
Cricket ^2^,^3^,^4^
Football ^1^,^3^
Vollyball ^4^,^1^
Now I want to write a query which will give me output like
name No_of_sports_played
Ajay 2
Amol 1
Sanjay 2
Vijay 2
So what will be Mysql query for this?
I agree with the above answers/comments that you are not using a database for what a database is for, but here is how you could calculate your table from your current structure in case you have no control over that:
See it in action here.
UPDATE: added the
IF(Played_by IS NULL,0,COUNT(*))instead ofCOUNT(*). This means that if an employee doesn’t play anything they’ll have a 0 as theirNum_Sports. See it here (I also added in those^characters and it still works.What it does is joins the Emp table to the Sports table if it can find the
Emp.idin the correspondingPlayed_bycolumn.For example, if we wanted to see what sports Ajay played (id=1), we could do:
The query I gave as my solution is basically the query above, with a
GROUP BY Emp.nameto perform it for each employee.The one modification is the use of
RLIKEinstead ofLIKE.I use
RLIKE '[[:<:]]employeeid[[:>:]]'instead ofLIKE '%employeeid%. The[[:<:]]symbols just mean “make sure the employeeid you match is a whole word”.This prevents (e.g.)
Emp.id1 matching the 1 in thePlayed_byof3,4,11,2.