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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With