MySQL Join 4 tables returning only 1 row

ash :

Sorry for my bad English, I have requirement to get data from mysql 4 table but it only return 1 row.

table 1

col_2 in tabl 1 contain numeric data as reference from Table 2 col_2

+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   A   |  4      |
| 2  |   B   |  5      |
| 3  |   C   |  6      |
+----+-------+---------+

table 2

+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   A   |  4      |
| 2  |   B   |  5      |
| 3  |   C   |  6      |
| 4  |   C   |  7      |
| 5  |   C   |  8      |
+----+-------+---------+

table 3

Table 3 col_1 has numeric value of table 1 id but most of theme will be the same id, and col_2 has numeric value of id from table 4

+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   1   |  1      |
| 2  |   1   |  2      |
| 3  |   1   |  3      |
| 4  |   2   |  4      |
| 5  |   2   |  5      |
| 6  |   4   |  8      |
| 7  |   4   |  1      |
| 8  |   5   |  2      |
| 9  |   5   |  5      |
| 10 |   5   |  8      |
| 11 |   5   |  9      |
| 12 |   5   |  10     |
+----+-------+---------+

table 4

+----+-------+
| id | col_1 |
+----+-------+
| 1  |   A   |
| 2  |   B   |
| 3  |   C   |
+----+-------+

the query I run to get data.

SELECT
    t1.id,
    t1.col_1,
    t2.col_1 as result_0,
    GROUP_CONCAT(t4.col_1) as result
FROM
    table_1 AS t1
LEFT JOIN table_2 AS t2
    ON t2.col_2 = t1.col_2
LEFT JOIN table_3 AS t3
    ON t3.col_1 = t1.id
LEFT JOIN table_4 AS t4
    ON t4.id = t3.col_2
WHERE t1.col_2 > 1
ORDER BY t1.id DESC

as you can see table 3 has deferent id from table 1 and table 4, both table has value so I want query to return me as bellow. it means I want the value from table 4 to be separated by comma.

+----+-----------+-----------+-----------+
| id | result_1  | result_2  | result_3  |
+----+-----------+-----------+-----------+
| 1  |   A       |    A      |    A,B,C  |
| 2  |   B       |    B      |    A,B    |
| 3  |   C       |    C      |    C,B    |  
+----+-----------+-----------+-----------+

UPDATE: as requested here is the fiddle of query.

SQL Fiddle http://sqlfiddle.com/#!9/3af0af/1 thanks

Sandeep Modak :

Based on the fiddle you posted

All you have to do is change your query to :-

SELECT
    t1.id,
    t1.name,
    t2.role as result_0,
    GROUP_CONCAT(t4.ct) as result
FROM
    table_one AS t1
LEFT JOIN table_tow AS t2
    ON t2.level = t1.level
 JOIN table_three AS t3                       //CHANGED LEFT JOIN TO JOIN
    ON t3.vid = t1.id
LEFT JOIN table_four AS t4
    ON t4.id = t3.cid
WHERE t1.level > 1
group by t1.id ORDER BY t1.id ASC            //ADDED group by t1.id AND CHANGED ORDER BY t1.id DESC TO ORDER BY t1.id ASC

Guess you like

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