Hi PRA,
Please refer below query.
SQL
CREATE TEMPORARY TABLE Fruits (
Id INT,
Name VARCHAR(20)
);
INSERT INTO Fruits VALUES(1,'Apple');
INSERT INTO Fruits VALUES(2,'Banana');
INSERT INTO Fruits VALUES(3,'Cherry');
CREATE TEMPORARY TABLE Person (
Id INT,
Name VARCHAR(20)
);
INSERT INTO Person VALUES(1,'Rustam');
INSERT INTO Person VALUES(2,'Muhammad');
INSERT INTO Person VALUES(3,'Sindbod');
INSERT INTO Person VALUES(4,'Sadriddin');
CREATE TEMPORARY TABLE Products (
Id INT,
PersonId VARCHAR(20),
FruitId INT
);
INSERT INTO Products VALUES(1,'1,3,4',1);
INSERT INTO Products VALUES(2,'1,2',3);
INSERT INTO Products VALUES(3,'2',2);
CREATE TEMPORARY TABLE TEMP2(SELECT t2.Id,group_concat(t1.name) as Name FROM products t2 LEFT JOIN person t1 ON find_in_set(t1.Id,t2.PersonId) GROUP BY t2.id);
CREATE TEMPORARY TABLE TEMP3(SELECT t2.id,t3.name FROM Products t2 JOIN Fruits t3 ON t2.FruitId = t3.Id);
SELECT TEMP2.Id,TEMP2.Name AS PersonName,temp3.Name FROM TEMP2 JOIN TEMP3 ON TEMP2.Id = TEMP3.Id ORDER BY TEMP2.Name DESC;
DROP TABLE temp2;
DROP TABLE temp3;
DROP TABLE fruits;
DROP TABLE person;
DROP TABLE products;
Output
Id |
PersonName |
Name |
1 |
Rustam,Sindbod,Sadriddin |
Apple |
2 |
Rustam,Muhammad |
Cherry |
3 |
Muhammad |
Banana |