【问题标题】:Sqlite left join composite keysSqlite 左连接复合键
【发布时间】:2018-10-18 22:22:32
【问题描述】:

为静态 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 正确制表。在我看来,这应该意味着 LEFT 加入:

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"

【问题讨论】:

  • @EbyJacob 嗨。当您编辑时,尤其是当您的编辑需要审核时,请尽您所能,包括删除问候、感谢等。还要检查格式化输出——这里的列标题与数据不一致。
  • 嗨。未来:用 [mvce] 更好地编写/接收/理解/回答重新编码的问题。这包括剪切 & 粘贴 & 可运行的代码。它包括一个明确的规范--代码应该为任意输入完成什么。自然,努力寻找和表达这不仅仅是询问的一部分,而是先于和指导编码。而且很难。 (对表/查询执行此操作的最佳方法是通过其行成员资格标准,即谓词。)(虽然每个函数/程序/系统也有一个输入-输出关系谓词。)

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


【解决方案1】:

左连接返回内连接行加上由空值扩展的不匹配的左表行。如果你认为你想要一个左连接,那么你需要识别相关的内连接。在这里,您似乎不知道表格和条件。但是您似乎至少希望每个可能的学生数据对都有一行;实际上,对于 (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 保存满足其左表成员资格条件and 的行,并使用右表的条件/谓词和每个列对右表is null 唯一的条件@ 987654328@。

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

(如果列 descriptionname 具有相同的名称,那么您必须在 natural join 之前重命名一个或使用 inner join using (student_id, data_id)。但同样,这将来自于编写适当的谓词。)

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 2012-08-03
    • 1970-01-01
    • 2011-12-21
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多