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?

Alex
  • 77
  • 1
  • 6

3 Answers3

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
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
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;
Poorna Senani Gamage
  • 1,246
  • 2
  • 19
  • 30
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
Chayan
  • 604
  • 5
  • 12
  • @Alex note that `left join` is really unnecessary. Inner join is sufficient. `Left join` is inefficient when you deal with bigger tables – Madhur Bhaiya Oct 07 '18 at 17:06
  • 1
    @MadhurBhaiya, Thanks for your valuable info. I have updated my answer. – Chayan Oct 07 '18 at 17:09
  • @MadhurBhaiya LEFT JOIN and INNER JOIN do different things, which should be the primary reason for choosing to use one over the other. – Strawberry Oct 07 '18 at 18:13
  • @Strawberry in this particular scenario. `left join` was unnecessary; that is why suggested that "inner join is sufficient" – Madhur Bhaiya Oct 07 '18 at 18:14
  • 1
    @MadhurBhaiya I think the statement that `left join is inefficient when you deal with bigger tables` is too simplistic an observation – Strawberry Oct 07 '18 at 18:19
  • @Strawberry point taken. Unfortunately cannot edit the comment now. – Madhur Bhaiya Oct 07 '18 at 18:20