0

see the below query table.

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 the following query

SELECT CONCAT(e.first_name, ' ', e.last_name) AS full_name
     , SUM(es.salary) AS total_salary
     , (SELECT GROUP_CONCAT(h.name) 
        FROM hobby h 
        INNER JOIN hobby 
            ON h.id = eh.fk_hobby_id
       ) AS hobby_name 
FROM employee_hobby eh
INNER JOIN employee e 
    ON e.id = eh.fk_employee_id
INNER JOIN employee_salary es 
    ON es.fk_employee_id = eh.fk_employee_id
GROUP BY eh.fk_employee_id;

but the in this query hobby_name raw gets multiple hobby_name names that are not defined in the hobby table. and I have to complete this task by using the subquery Here is my OUTPUT Image.enter image description here

2
  • Welcome to the DBA.SE community. Please take your time to read How to Ask and then consider reading up on Markdown Editor Help. Instead of posting screen shots consider using db<>fiddle and reading the helpful post Help me write this query in SQL from out Meta Site. Please also consider cleaning up the tags you are using. Your screenshot seems to be referencing a MySQL database, so you should remove the sql-server and sql-server-2012 tags. Thanks and good luck.
    – John K. N.
    Commented Jan 31, 2022 at 8:55
  • GROUP_CONCAT(h.name) -- Please elaborate on why there are multiple rows (names) for a single hobby.
    – Rick James
    Commented Jan 31, 2022 at 16:32

1 Answer 1

0

The lack of ddl and sample data makes it difficult to guess where the problem might be, but the following looks very suspicious:

INNER JOIN hobby 
    ON h.id = eh.fk_hobby_id

It means that you will multiply the number of hobbies for each employee with the cardinality of the hobby table. You may want to try:

SELECT CONCAT(e.first_name, ' ', e.last_name) AS full_name
     , SUM(es.salary) AS total_salary
     , (SELECT GROUP_CONCAT(h.name) 
        FROM hobby h 
        WHERE h.id = eh.fk_hobby_id
       ) AS hobby_name 
FROM employee_hobby eh
INNER JOIN employee e 
    ON e.id = eh.fk_employee_id
INNER JOIN employee_salary es 
    ON es.fk_employee_id = eh.fk_employee_id
GROUP BY eh.fk_employee_id;

Group by eh.fk_employee_id may or may not be correct, but it is hard to tell without ddl for the tables.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.