Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL request from two tables with FIND_IN_SET

I have two tables (MySQL):

  1. table_products: // cid (text) - comma separated categories list // id (int11)

    id   cid
    1    1,2,3        
    2    5,21,8
    3    2,4,15
    
  2. 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).

like image 209
XTRUST.ORG Avatar asked Apr 17 '13 12:04

XTRUST.ORG


People also ask

Can you select from two tables in MySQL?

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.

What is the use of Find_in_set in MySQL?

The FIND_IN_SET() function returns the position of a string within a list of strings.

How fetch data from two tables in join MySQL?

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).


1 Answers

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.

like image 103
fthiella Avatar answered Sep 28 '22 22:09

fthiella