0

I have two tables as follows
user table

user_id name
1 zia
2 john
3 raza

subject table

data_id user_id subject
1 1 Math
2 1 Chem
3 1 Bio
4 2 Math
5 2 Phy

when I am querying data i am getting results like this:

 [
{
    "user_id": "1",
    "name": "zia",
    "subject": [
        "Math",
        "Chem",
        "Bio"
    ]
},
{
    "user_id": "2",
    "name": "john",
    "subject": [
        "Math",
        "Phy"
    ]
},

]

My query is as follows

SELECT
users.user_id,
users.name,
GROUP_CONCAT(subjects.subject) sub
FROM
  `users`
  INNER JOIN subjects ON users.user_id = subjects.user_id
  GROUP BY
  subjects.user_id;

but actually I want to get data in following way:

the resuluts shown above are in such a way that if an entry from user table does not have coresponding enteries in subject table even then we must have user name and user id in our rsults as follows

 [
{
    "user_id": "1",
    "name": "zia",
    "subject": [
        "Math",
        "Chem",
        "Bio"
    ]
},
{
    "user_id": "2",
    "name": "john",
    "subject": [
        "Math",
        "Phy"
    ]
},
{
    "user_id": "3",
    "name": "Raza",
    
}

]

Here as you see that we have data in such a way that all the enteries from user table are shown alog with subject enteries from subject table if they match otherwise every user table entery is showing up with no affect.

*PLease help me in solving this issue **

3
  • You probably need to use LEFT JOIN instead of INNER JOIN, because you want to retrieve user without subject too Commented Jun 16, 2021 at 7:53
  • I will post it as solution Commented Jun 16, 2021 at 7:56
  • Here is the demo- sqlfiddle.com/#!9/65d80c/4 Commented Jun 16, 2021 at 8:07

1 Answer 1

1

You probably need to use LEFT JOIN instead of INNER JOIN, because you want to retrieve user without subject too

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.