Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query with Join, Count and Where

Tags:

I have 2 tables and am trying to do one query to save myself some work.

Table 1: id, category id, colour
Table 2: category id, category name

I want to join them so that I get id, category id, category name, colour

Then I want to limit it so that no "red" items are selected (WHERE colour != "red") Then I want to count the number of records in each category (COUNT(id) GROUP BY (category id).

I have been trying:

SELECT COUNT(table1.id), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour != "red"

But it just doesn't work. I've tried lots of variations and just get no results when I try the above query.

like image 987
Watters Avatar asked Jul 19 '13 16:07

Watters


People also ask

Can I use WHERE and count together in SQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

WHERE or join Which comes first?

The rows selected by a query are filtered first by the FROM clause join conditions, then the WHERE clause search conditions, and then the HAVING clause search conditions. Inner joins can be specified in either the FROM or WHERE clause without affecting the final result.

Can we use WHERE before join?

Normally, filtering is processed in the WHERE clause once the two tables have already been joined. It's possible, though that you might want to filter one or both of the tables before joining them. For example, you only want to create matches between the tables under certain circumstances.

How do I count rows in joined table?

Show activity on this post. $query_string = ' SELECT groups. userGroupID, userGroup, count(users. userGroupID) AS howMany FROM groups_table AS groups JOIN users_table AS users ON users.


2 Answers

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name
like image 80
John Woo Avatar answered Sep 28 '22 08:09

John Woo


SELECT COUNT(*), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name 
like image 44
Nenad Zivkovic Avatar answered Sep 28 '22 08:09

Nenad Zivkovic