如何根据两列的两个条件进行 SQL 查询?
How can I do SQL query based on two conditions on two columns?
see the EARD scenario
Major_applied_for table
id
preference
application_number (fk)
major_code (fk)
1
1
2
1
2
1
1
1
3
3
3
1
4
2
1
2
5
2
2
2
一些说明:
• 专业table代码属性为(1)计算机科学CS,(2)工商管理BMS等等。
• Major_Applied_For 的偏好属性为 1、2 或 3(1 表示第一个
选择,2 为第二选择,3 为第三选择)
.
.
.
这是一个table解决了多对多的关系,我想得到所有第一选择CS,第二选择BMS的申请号。
我试过这个 sql 语句,但它在逻辑上是不正确的。
SELECT m.id, CONCAT(m.fname, " ", m.lname) AS 全名, app.number AS application_no
FROM applicant m, application app, major_applied_for mjaf
其中 ((mjaf.major_code = 1 AND mjaf.preference = 1) AND (mjaf.major_code = 2 AND mjaf.preference = 2) AND (mjaf.application_number = app.number AND app.applicant_id = m.id));
我该如何解决这个问题?
查找以 CS 作为第一优先的申请人,查找以 BMS 作为第二优先的申请人。内部加入这两个集合并检查它们的名称。
with first_cs as (
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 1 and b.name = 'CS'
inner join application c on a.application_number = c.number ), second_bms as(
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 2 and b.name = 'BMS'
inner join application c on a.application_number = c.number ) select fname,
lname from first_cs a inner join second_bms b on a.applicant_id = b.applicant_id
inner join applicant c on a.applicant_id = c.id
see the EARD scenario
Major_applied_for table
id | preference | application_number (fk) | major_code (fk) |
---|---|---|---|
1 | 1 | 2 | 1 |
2 | 1 | 1 | 1 |
3 | 3 | 3 | 1 |
4 | 2 | 1 | 2 |
5 | 2 | 2 | 2 |
一些说明:
• 专业table代码属性为(1)计算机科学CS,(2)工商管理BMS等等。
• Major_Applied_For 的偏好属性为 1、2 或 3(1 表示第一个 选择,2 为第二选择,3 为第三选择) . . .
这是一个table解决了多对多的关系,我想得到所有第一选择CS,第二选择BMS的申请号。
我试过这个 sql 语句,但它在逻辑上是不正确的。
SELECT m.id, CONCAT(m.fname, " ", m.lname) AS 全名, app.number AS application_no FROM applicant m, application app, major_applied_for mjaf 其中 ((mjaf.major_code = 1 AND mjaf.preference = 1) AND (mjaf.major_code = 2 AND mjaf.preference = 2) AND (mjaf.application_number = app.number AND app.applicant_id = m.id));
我该如何解决这个问题?
查找以 CS 作为第一优先的申请人,查找以 BMS 作为第二优先的申请人。内部加入这两个集合并检查它们的名称。
with first_cs as (
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 1 and b.name = 'CS'
inner join application c on a.application_number = c.number ), second_bms as(
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 2 and b.name = 'BMS'
inner join application c on a.application_number = c.number ) select fname,
lname from first_cs a inner join second_bms b on a.applicant_id = b.applicant_id
inner join applicant c on a.applicant_id = c.id