3

I have 2 tables, User and Grade.

Table User

Class_ID | Name
100      | Alex
101      | Anna

Table Grade

Class_ID  | Teacher  | Subject  |  Time
  100     |   Join   |  English |  9:00
  101     |   ...    |  Math    |  10:00 

Query all the table User, I run:

SELECT * FROM User WHERE class_ID=100;

Query all the table Grade, I run:

SELECT * FROM Grade WHERE class_ID=100;

How can I return

Name | Class_ID  | Teacher  | Subject  |  Time
Alex |  100      |   Join   |  English |  9:00

with just a single query?

5
  • 2
    Think INNER JOIN. Please add sample data and expected output to the question. Commented Oct 7, 2018 at 16:43
  • I have updated. Commented Oct 7, 2018 at 16:55
  • 1
    Please add expected output also. Commented Oct 7, 2018 at 16:56
  • Ok. I updated :) Commented Oct 7, 2018 at 16:58
  • Give MySQL user guide a read in the JOIN section... It'll explain a lot of how to make queries using multiple tables Commented Oct 7, 2018 at 17:06

3 Answers 3

2

Try the following:

SELECT  u.Name, 
        u.Class_ID, 
        g.Teacher, 
        g.Subject, 
        g.Time 
FROM `User` AS u
JOIN Grade AS g 
  ON u.Class_ID = g.Class_ID 
WHERE u.Class_ID = 100
Sign up to request clarification or add additional context in comments.

Comments

1

You can use JOIN query. Get an idea from this.

SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

Comments

1
SELECT  u.Name, u.Class_ID, g.Teacher, g.Subject, g.Time from User u

INNER JOIN Grade g ON u.Class_ID = g.Class_ID ORDER BY u.Class_ID

6 Comments

@Alex note that left join is really unnecessary. Inner join is sufficient. Left join is inefficient when you deal with bigger tables
@MadhurBhaiya, Thanks for your valuable info. I have updated my answer.
@MadhurBhaiya LEFT JOIN and INNER JOIN do different things, which should be the primary reason for choosing to use one over the other.
@Strawberry in this particular scenario. left join was unnecessary; that is why suggested that "inner join is sufficient"
@MadhurBhaiya I think the statement that left join is inefficient when you deal with bigger tables is too simplistic an observation
|

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.