SQL multi-Table query

Source: Internet
Author: User

 

Scenario 1:

Now we have two tables: one student table and one gender table. Student: ID name gender. Gender: Key Value

 

The following values are available:

Student:

001 XY 1

002 xyy 1

003 Xiaohong 0

 

Gender

0 female

1 male

2 others

 

First, let's look at a table student. I want to find male students.

Select ID, name, gender from student where gender = '1 ';

 

We can query multiple tables and find male students. The gender is not 0, 1, 2, but Chinese characters.

Select S. ID, S. Name, G, Value

From student s, Gender g

Where S. Gender = '1'

And G. Key = S. Gender (correct) // two records

 

Have you seen it? We need to write not only S. Gender = '1' but also G. Key = S. Gender. That is to say, you must not only determine the value equals to what, but also write the equality relationship of the associated fields.

 

Select S. ID, S. Name, G, Value

From student s, Gender g

Where S. Gender = '1' (error) // 2*3 = 6 records 2 male students * 3 Gender table records (flute)

 

 

 

Select S. ID, S. Name, G, Value

From student s, Gender g

Whereg. Key = S. Gender (error) // 3 Records, 3 students, regardless of gender

 

 

Scenario 2:

 

Now we have two tables, one student table and one parameter CS table. Student: ID name gender, status. CS: Key Value Name

 

The following values are available:

Student:

001 XY 1 0

002 XY 1 0

003 XH 0 0

 

CS

Gender 0 female

Gender 1 male

Gender 2 others

Status 0 at school

Status 1 leaves school

 

Now I want to retrieve the name, gender, and school status.

Select S. Name, XB. MC, ZT. MC

From student s,

(Select key value name from CS where key = 'gender') XB,

(Select key value name from CS where key = 'status') zt

Where S. Gender = XB. Value

And S. Status = ZT. value;

 

In this case, we cannot associate two tables as simple as in Case 1. You can't CS. Key, gender, or status.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.