Please refer below tables and fields.
Create an “employee” database and 4 tables (hobby, employee, employee_salary, employee_hobby).
hobby: id, name
employee: id, first_name, last_name, age, mobile_number, address
employee_salary: id, foreign key of employee, salary
employee_hobby: id, foreign key of the employee, foreign key of hobby
I execute this query as follows:
SELECT CONCAT(e.first_name, ' ', e.last_name) AS full_name, SUM(es.salary) AS total_salary,
(SELECT GROUP_CONCAT(h.name)
FROM hobby AS h
INNER JOIN hobby ON h.id = eh.fk_hobby_id) AS hobby_name
FROM employee_hobby AS eh
INNER JOIN employee AS e ON e.id = eh.fk_employee_id
INNER JOIN employee_salary AS es ON es.fk_employee_id = eh.fk_employee_id
GROUP BY eh.fk_employee_id;
But I fetch all same hobby name in single row for particular record. output image
I need hobby_name for every record like sports,gaming or gaming,travelling etc.
This is not correct:
...
(SELECT GROUP_CONCAT(h.name)
FROM hobby AS h
INNER JOIN hobby ON h.id = eh.fk_hobby_id) AS hobby_name
FROM employee_hobby AS eh
...
Just join hobby
table in the query like other tables:
SELECT CONCAT(e.first_name, ' ', e.last_name) AS full_name,
SUM(es.salary) AS total_salary,
GROUP_CONCAT(h.name)
FROM employee_hobby AS eh
INNER JOIN hobby h ON h.id = eh.fk_hobby_id
INNER JOIN employee AS e ON e.id = eh.fk_employee_id
INNER JOIN employee_salary AS es ON es.fk_employee_id = eh.fk_employee_id
GROUP BY eh.fk_employee_id;
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.