PostgreSQL使用JOIN语句查询多个表

问题描述 投票:1回答:1

我对SQL和Postgres很陌生。我遇到过一个案例,我觉得应该用JOIN,但实际上看起来比较复杂,我不知道该用什么查询。

所以我有3张表:学生、学校和用户。

用户:

       Column        |          Type          | Collation | Nullable |              Default              
---------------------+------------------------+-----------+----------+-----------------------------------
 id                  | bigint                 |           | not null | nextval('users_id_seq'::regclass)
 public_id           | uuid                   |           | not null | uuid_generate_v4()
 first_name          | character varying(50)  |           | not null | 
 last_name           | character varying(50)  |           | not null | 
 username            | character varying(50)  |           | not null | 
 email               | character varying(255) |           |          | 
 password            | character varying(255) |           | not null | 
 role                | character varying(20)  |           | not null | 
 username_repetition | integer                |           |          | 1

学生:

  Column   |  Type  | Collation | Nullable |               Default                
-----------+--------+-----------+----------+--------------------------------------
 id        | bigint |           | not null | nextval('students_id_seq'::regclass)
 class_id  | bigint |           | not null | 
 school_id | bigint |           | not null | 
 user_id   | bigint |           | not null | 

学校:

Column    |          Type          | Collation | Nullable |               Default        
--------------+------------------------+-----------+----------+-------------------------------------
 id           | bigint                 |           | not null | nextval('schools_id_seq'::regclass)
 name         | character varying(100) |           | not null | 
 short_name   | character varying(50)  |           | not null | 
 phone_number | character varying(30)  |           | not null | 
 postal_code  | character varying(30)  |           | not null | 
 adress       | character varying(255) |           | not null | 
 city         | character varying(50)  |           | not null | 
 county       | character varying(50)  |           | not null | 

我想用SELECT查询来获取一个学生用户的用户名_重复,只有当这个学生被分配到一个特定的学校时才可以。我怎样才能实现这个目标?如果你需要进一步的信息,请告诉我。谢谢你!我对SQL很陌生。

sql postgresql
1个回答
1
投票

试试这个。

SELECT username_repetition FROM users u
INNER JOIN students std ON std.user_id = u.id
INNER JOIN schools sch ON std.school_id = sch.id AND sch.name = 'School name'

查询用名字来过滤学校 sch.name = ?您可以通过任何其他方式进行过滤,例如邮政编码。sch.postal_code = ?.

如果用户不是学生或没有链接到学校,查询将不返回结果。

© www.soinside.com 2019 - 2024. All rights reserved.