Sqlite左连接复合键

时间:2018-05-08 21:30:23

标签: sqlite left-join composite-primary-key cross-join natural-join

展开静态ORM的SQLite数据透视查询,问题是缺少值需要空值。

table student
student_id | name
    1       "Fred"
    2       "Tim"
PK(`student_id`)

table grade 
student_id | data_id | grade
    1           1       5.0
    1           2       5.0
    2           2       5.0
PK(`student_id`,`data_id`),
FK(student.studentid)
FK(data.data_id)

table data 
data_id | description
   1       "summer"
   2       "autumn"
PK(`data_id`)

我需要结果包含静态ORM的空行才能正确显示。在我看来,这应该意味着左翼加入:

SELECT * FROM student
join grade using (student_id)
LEFT OUTER JOIN data
ON grade.data_id = data.data_id

由于Tim没有参加夏季考试,所以student_id没有排表等级中的data_id PK_pair(2,1)。

查询当前返回:

sID |  name  | dID | grade | description
"1"   "Fred"   "1"   "5.0"   "summer"
"1"   "Fred"   "2"   "5.0"   "autumn"
"2"   "Tim"    "2"   "5.0"   "autumn"

结果中缺少此行:

sID |  name  | dID | grade | description
"2"    "Tim"   "1"    null    "summer"

1 个答案:

答案 0 :(得分:2)

左连接返回内部连接行以及由空值扩展的不匹配的左表行。如果您认为需要左连接,则需要识别关联的内连接。在这里,你似乎不知道表格和表格。条件。但是你似乎至少想要为每个可能的学生数据对排一行;事实上,对于(student_id,name)& (data_id,description)。所以那些必须在左表中。此外,列级别为空,因此可能与正确的表格有关。也许你想要:

select *
from students
natural join data
left natural join grade

我选择了该查询,因为它(在公共列中没有空值,没有重复的行):

/* rows where
    student [student_id] has name [name]
and term [data_id] has description [description]
and (student [student_id] got grade [grade] in term [data_id]
    or not exists grade [student [student_id] got grade [grade] in term [data_id]]
    and [grade] is null
    )
/*
  

Sqlite左连接复合键

虽然约束告诉我们有关查询结果的一些事情,但它们不需要查询。所需要的是查询结果的成员资格标准,即其(特征)谓词。在这种情况下我给了代码注释。注意它是如何从基表构建的。标准/谓词:

  • natural join包含满足其表格and的行。标准/谓词。
  • left natural join使用正确的表格标准/谓词&amp ;;保存符合其左表格会员资格标准and的行,并使用某个or。每个列对右表is null唯一的条件。

Is there any rule of thumb to construct SQL query from a human-readable description?

(如果列descriptionname具有相同的名称,则您必须在natural join之前重命名,或使用inner join {{1但是,再一次,这将来自组成适当的谓词。)