sql连接表和查找差异

ndh0cuux  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(441)

我有一个包含以下模式的表:

Table1
    +------------------+--------------------+-------------------+-------------+-------------+
    |student_id|project_id|name|project_name|approved|evaluation_type|grade| cohort_number|

我还有一张table,上面有:

Table2
    +-------------+----------+
    |cohort_number|project_id|

我的问题是:我想为每个学生获得他尚未完成的项目(没有行)。我知道他应该做的所有项目都是通过核对你的号码。基本上我需要两张table之间的“差异”。我想用缺失的条目填充表1,方法是将表2的项目id与队列编号进行比较。
我不确定我是否清楚。我试着使用左连接,但我只得到匹配的记录(我需要相反的答案)
例子:

Table1

    |student_id|project_id|name|           project_name| approved|evaluation_type|             grade|cohort_number|
    +----------+----------+--------------------+------+--------------------+--------+---------------+------------------
    |        13|        18|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|
    |        13|         7|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|
    |        13|        27|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|

表2

+-------------+----------+
|cohort_number|project_id|
+-------------+----------+
|            3|        18|
|            3|        27|
|            4|        15|
|            3|         7|
|            3|        35|

我想要:

|student_id|project_id|name|           project_name| approved|evaluation_type|             grade|cohort_number|
    +----------+----------+--------------------+------+--------------------+--------+---------------+------------------
    |        13|        18|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|
    |        13|         7|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|
    |        13|        27|Name|  project/sd-03-bloc...|    true|       standard|               1.0|            3|
    |        13|        35|Name|  project/sd-03-bloc...|    false|       standard|                 0|            3|

提前谢谢

baubqpgj

baubqpgj1#

如果我跟对了你,你会明白的 (student_id, cohort_number, name) 元组来自 table1 ,然后从 table2 . 这基本上给你一个学生应该完成的每个项目一行。
然后你可以带上 table1 用一个 left join . "缺失的“项目”由 null 列中的值 project_name , approved , evaluation_type , grade .

select 
    s.student_id,
    t2.project_id,
    s.name,
    t1.project_name,
    t1.approved,
    t1.evaluation_type,
    t1.grade,
    s.cohort_number
from (select distinct student_id, cohort_number, name from table1) s
inner join table2 t2 
    on  t2.cohort_number = s.cohort_number
left join table1 t1
    on  t1.student_id = s.student_id 
    and t1.project_id = t.project_id

相关问题