I have two tables (MySQL):
table_products: // cid (text) - comma separated categories list // id (int11)
id cid
1 1,2,3
2 5,21,8
3 2,4,15
table_categories
id name parent
1 Cat1 0
2 Cat2 0
3 Cat3 0
4 Cat4 0
This is my request:
SELECT `id`, `name`, `parent`
FROM `table_categories`
ORDER BY `parent` ASC, `id` ASC;
How can I perform the request above and also get the number of products in each category (from table_products). May be using (FIND_IN_SET).
Based on this e-mail from one user (excerpt only): Multitable SELECT (M-SELECT) is similar to the join operation. You select values from different tables, use WHERE clause to limit the rows returned and send the resulting single table back to the originator of the query.
The FIND_IN_SET() function returns the position of a string within a list of strings.
Ans: Joining two tables in SQL can be done in four major ways: Inner Join (returns rows with matching columns), Left Join (ALL records in the left table and matching records in the right table), Right Join (ALL records in the right table and matching records in the left table), and Union (removes duplicates).
If every category is present in table_categories
, then you could use this:
SELECT table_categories.name, count(table_products.id)
FROM
table_categories LEFT JOIN products
ON FIND_IN_SET(table_categories.id, products.cid)
GROUP BY table_categories.name
If table_categories.id is present in products.cid then FIND_IN_SET will return a non-zero value, and the join will succeed.
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