Click here to Skip to main content
16,016,750 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello! I need to show title categories from table Menu and count notes from table Cars, where menu.id = cars.marka. So, i wanna get the next: BMW (4), where 4 is number of notes from table Cars.
I tried such, but it not correct:

SQL
SELECT menu.title, COUNT( cars.id_cars ) AS total
FROM menu
LEFT JOIN cars ON (cars.marka = menu.id AND menu.parent_id =96
AND menu.block =3)
Posted

Jardin1 wrote:
i wanna get the next: BMW (4), where 4 is number of notes from table Cars.

In this case you need to use HAVING clause as follow:
SQL
DECLARE @pid INT
DECLARE @blo INT
DECLARE @cou INT

SET @pid = 96
SET @blo = 3
SET @cou = 4 --no. of BMW ;)

SELECT m.title
FROM menu AS m LEFT JOIN cars AS c ON c.marka = m.id 
WHERE m.parent_id =@pid AND m.block =@blo
GROUP BY m.title
HAVING COUNT(c.id_cars) = @cou

More:
HAVING (T-SQL)[^]
GROUP BY (T-SQL)[^]
Aggregate functions (T-SQL)[^]
 
Share this answer
 
v4
Do like below...
SQL
SELECT 
      menu.title, 
      COUNT(cars.id_cars) AS total
FROM 
      menu
LEFT JOIN 
      cars 
ON (cars.marka = menu.id AND menu.parent_id = 96 AND menu.block = 3)
GROUP BY menu.title
 
Share this answer
 
You need a GROUP BY menu.title statement for the COUNT to work,
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900