Reputation: 41
I have two tables. My first table is animal_tbl the second one is animal_ate_tbl and food_type_tbl.
this is the visualization of animal_tbl:
animal_ate_tbl:
food_type_tbl
I want a query that will select the: animal_num, animal_fname+animal_lname, count of banana she ate and count of apple she ate and the count of chico she ate. I created my own query however it is outputing the wrong result. can you help me? I promise to vote up the one who can help me :)) this is the sample query i got but is wrong:
select
a.animal_num,
a.animal_fname,
a.animal_lname,
(
SELECT
COUNT(*)
FROM
animal_ate_tbl
WHERE
food_id = x22
group by
animal_id
) as banana,
(
SELECT
COUNT(*)
FROM
animal_ate_tbl
WHERE
food_id = x33
group by
animal_id
) as banana,
(
SELECT
COUNT(*)
FROM
animal_ate_tbl
WHERE
food_id = x44
group by
animal_id
) as chico
from
animal_tbl as a,
animal_ate_tbl
group by
a.animal_num = animal_id
However, this should be the output:
I will promise that i will give an upvote to those who will answer. btw the table is only a sample table that im doing.
Upvotes: 0
Views: 28
Reputation: 4939
Try this instead:
SELECT
A.animal_num,
CONCAT(IFNULL(A.animal_fname,''),' ', IFNULL(A.animal_lname,'')) fullName,
(SUM(IF(C.food_type='banana',1,0))) banana,
(SUM(IF(C.food_type='apple',1,0))) apple,
(SUM(IF(C.food_type='chico',1,0))) chico
FROM animal_tbl A LEFT JOIN animal_ate_tbl B
ON A.animal_nu=B.animal_id LEFT JOIN food_type_tbl C
ON B.food_id=C.food_id
GROUP BY A.animal_num,
CONCAT(IFNULL(A.animal_fname,''),' ', IFNULL(A.animal_lname,''));
Upvotes: 1