Select unique value from table has null columns

Tùng Nguyễn :

I have a detail_product table.

the product_id, category_id, color_id and size_id are foreign key for the table product, category, color and sizerespectively

id | product_id | category_id | color_id | size_id
---------------------------------------------------
1  |     1      |      1      |   null   |   null
2  |     1      |      2      |   null   |   null
3  |     1      |     null    |    1     |   null
4  |     1      |     null    |   null   |    2
5  |     2      |      2      |   null   |   null
6  |     2      |     null    |    2     |   null
7  |     3      |      1      |   null   |   null
8  |     3      |      2      |   null   |   null
9  |     3      |     null    |    1     |   null
10 |     3      |     null    |    2     |   null

How I can select the product which satisfies conditions. I got stuck when select because of the null value in these columns. For example, I want to select all products which belong to category 1 and category 2 and have color is 1 then which sql statement should write? (In that example my expected value is that product_id return 1 and 3).

Does anyway to skip these null columns or some statements to solve my problem?

I have tried this but it not work:

SELECT detail_product.product_id 
FROM  `detail_product` 
WHERE  detail_product.category_id = 1 
AND    detail_product.category_id = 2 
AND    detail_product.color_id = 1
Akina :
SELECT product_id 
FROM detail_product
GROUP BY product_id 
HAVING FIND_IN_SET(1, GROUP_CONCAT(category_id)) -- category_id=1 must exist
   AND FIND_IN_SET(2, GROUP_CONCAT(category_id)) -- category_id=2 must exist
   AND FIND_IN_SET(1, GROUP_CONCAT(color_id))    -- color_id=1 must exist

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27793&siteId=1