0

I want to know how i can write a mysql query which checks how many record exists in other table ?

table 1 : names

id name
-- ----
4  john
5  mike
6  jenny

table 2 : cars

id name_id car
-- ------- ---
1   4      bmw
2   4      wv
3   6      honda

query = "SELECT * FROM names WHERE id = '4'" <- in that query i also want to check how many records there are in the cars table or if there is any ?

3 Answers 3

3

This should do it:

SELECT names.id, name, COUNT(car) as 'cars'
FROM names LEFT JOIN cars ON names.id = cars.nameid 
WHERE names.id = '4'
GROUP BY names.id, name
Sign up to request clarification or add additional context in comments.

3 Comments

this is more efficient that using a sub query.
@Hamish, OP should try all solutions and draw his conclusions from there. Using SQL Server, performing the group by in the join is twice as fast.
The title and tags specify MySQL. In current MySQL versions subqueries are very poorly optimized. Refer mysqlperformanceblog.com/2010/10/25/…. Hence the upvote.
1
SELECT n.*, COUNT(c.*) FROM names n, cars c WHERE n.id = 4

You can also name the column:

SELECT n.*, COUNT(c.*) AS `num_cars` FROM names n, cars c WHERE n.id = 4

1 Comment

That would return all records where the cars.id = 4 not the names.id = 4, a simple change though
1

Add the amount of cars for each person in an additional LEFT OUTER JOIN

SELECT  n.*, c.cnt
FROM    names n
        LEFT OUTER JOIN (
          SELECT  name_id, cnt = COUNT(*)
          FROM    cars
          GROUP BY
                  name_id
        ) c ON c.name_id = n.id
WHERE   ID = 4

If performance is an issue, you can add the condition to the left join at the expense of maintainability.

SELECT  n.*, c.cnt
FROM    names n
        LEFT OUTER JOIN (
          SELECT  name_id, cnt = COUNT(*)
          FROM    cars
          WHERE   name_id = 4 -- Condition needs to be updated in two places
          GROUP BY
                  name_id
        ) c ON c.name_id = n.id
WHERE   ID = 4

2 Comments

don't know what Ahmet vardar is expecting, but with this query, he doesn't get "mike" with "0" cars... i think the left join that JonVD posted would be the better solution (as it lists all names, the ones without cars, too)
@oezi, you are right, I've changed the INNER to LEFT OUTER JOIN.

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.