gpt4 book ai didi

sql - Table Per Type 数据检索

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:38 25 4
gpt4 key购买 nike

我关注了多篇文章,其中大部分使用 Entity Framework 查询来展示如何检索数据。但是,如果您考虑以下表结构:

Table Per Type sample

如果我只想使用纯 SQL 查找 ID 为 2 的汽车的详细信息,我是否应该使用该 ID 在所有继承表(本例中为“二手车”和“新车”)中查找匹配项?

在“新车”表中找到它之前,不会导致对“二手车”表进行全面扫描吗?或者有什么方法可以让我知道我必须直接转到“新车”表?

或者我对 Table-Per-Type 设计的假设是错误的?

最佳答案

如果你想找到年份,你可以这样做:

select c.*, coalesce(uc.year, nc.year) as year,
(case when uc.id is not null then 'Used' else 'New' end) as which
from car c left join
usedcar uc
on c.id = uc.id left join
newcar nc
on c.id = nc.id
where c.id = 2;

您应该将 id 声明为所有表中的主键(尽管我将其命名为 carId)。然后将不进行扫描。只是索引查找。

换句话说,你的设计没问题。您可能需要各种约束来确保汽车是新车还是二手车,但不能同时是这两种。

关于sql - Table Per Type 数据检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41988887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com