2

I need to get query like this:

Name COUNT
King 3
Queen 1
Single 0

but when I use query

SELECT bedtype.bedTypeName ,COUNT(room_bed.bedTypeID) FROM room_bed
LEFT JOIN bedtype ON bedtype.bedTypeID = room_bed.bedTypeID
WHERE room_bed.roomID = 3
GROUP BY bedtype.bedTypeName

I got this:

Name COUNT
King 3
Queen 1

How Can I get above result ?

Table 1 : bedType

ID bedTypeName
1 King
2 Queen
3 Single

Table 2 : room_bed

ID bedTypeID roomID
1 1 3
2 1 3
3 1 3
4 2 3
2
  • have you tried using SUM? Commented Feb 1, 2021 at 7:09
  • yes. I tried but it can't. Commented Feb 1, 2021 at 7:13

3 Answers 3

5

You have a couple of problems. Firstly, you need to LEFT JOIN from bedType to room_bed to ensure that you get all bed types in the output result. Secondly, you cannot have a condition on the LEFT JOINed table in a WHERE clause; otherwise you convert that LEFT JOIN into an INNER JOIN (see the manual). Change your query to this:

SELECT b.bedTypeName AS Name, COUNT(r.id) AS `Count`
FROM bedType b
LEFT JOIN room_bed r ON b.ID = r.bedTypeID AND r.roomID = 3
GROUP BY b.bedTypeName

Output:

Name    Count
King    3
Queen   1
Single  0

Demo on db-fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

try invert the tables and use SUM checking for null

SELECT bedtype.bedTypeName , SUM(ifnull(room_bed.bedTypeID,0)) FROM bedtype
LEFT JOIN  room_bed  ON bedtype.bedTypeID = room_bed.bedTypeID
WHERE room_bed.roomID = 3
GROUP BY bedtype.bedTypeName

5 Comments

I getting old result.
Isn't it isnull instead of ifnull?
oh right my bad I read it too fast and thought about sql server!
@MMMMMMM . update you question and add a valid data sample (not only the expected result) .. add your tables scheda
I Updated. If something goes wrong I am sorry.
0

Replace these two and they will be fine

bedtype.bedTypeID = room_bed.bedTypeID

2 Comments

but SQL already like SELECT bedtype.bedTypeName ,COUNT(room_bed.bedTypeID) FROM room_bed LEFT JOIN bedtype ON "bedtype.bedTypeID = room_bed.bedTypeID" WHERE room_bed.roomID = 3 GROUP BY bedtype.bedTypeName or not ?
Please add some explanation to your answer such that others can learn from it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.