MySQL – Get Relation Data on Comma Separated Values

MySQL

I am an average in database operation but I never deal with a database having values in comma separated manner. As I want the result from both table.

I have one table "Form table"

+------+-----------------+
| id   | Fname           |
+------+-----------------+
| 1    | f_934_tarun1    |
| 2    | f_934_tarun2    |
| 3    | f_934_a1        |
+------+-----------------+

2nd table "user assigned form table"

+------+--------------------------------+
| u_id | Fname                          |
+------+--------------------------------+
| 1    | f_934_xyz,f_934_tarun1         |
| 2    | f_934_tarun2,f_934_fhh         |
| 3    | f_934_ttt,f_934_nhj            |
| 4    | f_934_a1,f_934_t5trt           |
+------+--------------------------------+

I want to get all user ids who has any of form listed in form table. So here the output will be:

+------+
| u_id |
+------+
| 1    |
| 2    |
| 4    |
+------+

Every help will be appreciated.

Best Answer

You can use MySQL INSTR to achieve this:

SELECT U.u_id
FROM Userassigned U
JOIN FormTable F ON INSTR(U.Fname, F.Fname) > 0;

SQL Fiddle for the same: http://sqlfiddle.com/#!9/6f27ce/1