Search code examples
mysqljoinfind-in-set

Left Join with Find in set


I have tables as follows :

TABLE A
+-----+---------------+-------------+
| ID  | DNR_DETAIL_ID | DESCRIPTION |
+-----+---------------+-------------+
|  1  |       1       |   DESC A    |
+-----+---------------+-------------+
|  2  |       2       |   DESC B    |
+-----+---------------+-------------+
|  3  |       3       |   DESC C    |
+-----+---------------+-------------+


TABLE B
+--------+---------------+
| DNR_ID | DNR_DETAIL_ID |
+------------------------+
|   1    |     1,2       |
+--------+---------------+
|   2    |       3       |
+--------+---------------+

As you can see, DNR_DETAIL_ID columns are common in both tables. What I want to do, left joining both tables with field values ( null or not )

THE RESULT SHOULD BE (IF DNR_ID = 1) :
+-------------+---------+
| DESCRIPTION | CHECKED |
+-------------+---------+
|    DESC A   |    1    |
+-------------+---------+
|    DESC B   |    1    |
+-------------+---------+
|    DESC C   |    0    |
+-------------+---------+

Solution

  • Thank you so much guys. I have tried all of your suggestions but none of them work. Interesting thing is that code works well in sqlfiddle ( same schema and values ) but not working in local environment! Here is the query that working in local.

    /** 
     * DNR_DETAIL_DESC IS TABLE A
     * DNR_LIST IS TABLE B
     */
    SELECT A.DNR_DETAIL_DESC,
       CASE WHEN B.DNR_ID IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
    FROM MD_DNR_DETAIL A
    LEFT JOIN (SELECT * FROM DNR_LIST WHERE DNR_ID = 1) AS B
       ON FIND_IN_SET(A.DNR_DETAILT_ID, B.DNR_DETAIL_ID)