I have a question.I have 3 tables like shown below :
Table company
id_comp comp_name
1 company1
2 company2
3 company3
4 company4
Table main
id_main code description id_comp
1 100 Project 1 1
2 200 Project 2 1
3 300 Project 3 2
4 400 Project 4 3
Table sub_main
id_sub_main sub_code sub_description id_main
1 101 Project 1.1 1
2 102 Project 1.2 1
3 201 Project 2.1 2
4 202 Project 2.2 2
5 203 Project 2.3 2
6 401 Project 4.1 4
7 402 Project 4.2 4
The question : what is the best mysql or php code to produce a table like shows below :
company code description sub_code sub_description
company1 100 Project 1 101 Project 1.1
102 Project 1.2
200 Project 2 201 Project 2.1
202 Project 2.2
203 Project 2.3
company3 400 Project 4 401 Project 4.1
402 Project 4.2
The answer that I got mixed with Neels code :
company code description sub_code sub_description
1 100 Project 1 101 Project 1.1
1 102 Project 1.2
1 200 Project 2 201 Project 2.1
1 202 Project 2.2
1 203 Project 2.3
3 400 Project 4 401 Project 4.1
402 Project 4.2
You can try this MySQL
query:
SELECT company.comp_name,
GROUP_CONCAT(jointable.code ORDER BY jointable.code SEPARATOR '\n') as code,
GROUP_CONCAT(jointable.description ORDER BY jointable.code SEPARATOR '\n') as description,
GROUP_CONCAT(jointable.sub_code ORDER BY jointable.code SEPARATOR '\n') as sub_code,
GROUP_CONCAT(jointable.sub_description ORDER BY jointable.code SEPARATOR '\n') as sub_description
FROM
(SELECT main.id_comp,
main.code,
main.description,
GROUP_CONCAT(sub_main.sub_code ORDER BY sub_main.sub_code SEPARATOR '\n') as sub_code,
GROUP_CONCAT(sub_main.sub_description ORDER BY sub_main.sub_code SEPARATOR '\n') as sub_description
FROM main
INNER JOIN sub_main ON main.id_main = sub_main.id_main
GROUP BY main.id_main) jointable
INNER JOIN company ON company.id_comp = jointable.id_comp
GROUP BY company.id_comp;
See a Working SQL Fiddle here:
SELECT a.code, a.description, b.sub_code, b.sub_description from main as a, sub_main as b where a.id_main = b.id_main group by a.code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.