哪一个更可取?在table中加一列还是使用子查询获取数据?
Which of these is preferable? Adding a column to the table or using sub-query to get data?
我的意思是,Table A 有 5 列。我有一个 SP,我用它从 Table A 中获取 3 列,从 Table B 中获取一列。现在,将 Table B 中的列添加到 [=13 会更好吗? =] A 或使用该 SP 中的子查询从 Table B 中获取该列?
您的问题仍然令人困惑,看起来您还没有理解如何使用关系数据库。那么让我试着解释一下:
假设您有两个 table:
客户端
client_number
first_name
last_name
date_of_birth
...
订单
order_number
client_number
order_date
...
这是两个独立的table,以便有一个规范化的关系数据库。订单table包含客户编号,因此您可以在客户table中查询客户姓名和出生日期。为了了解客户是否被允许订购某些物品,出生日期可能很重要。但是您不想在每个订单中都存储出生日期 - 它不会改变。
如果你想查询年龄你可以使用子查询:
select
order_number,
order_date,
quantity,
(
select date_of_birth
from client c
where c.client_number = o.client_number
)
from order o
where item = 'whisky';
但大多数时候你会简单地 加入 tables:
select
o.order_number,
o.order_date,
o.quantity,
c.date_of_birth,
c.first_name,
c.last_name
from order o
join client c on c.client_number = o.client_number;
然而,您 不会 更改您的 table 并邀请具有所有问题的冗余,而不必加入。您将数据库设计为结构良好的关系数据库,而不是使您的最新查询易于编写。使用连接和子查询非常非常普遍,必须使用它们通常表明您的数据库构建得很好。
我认为这是你查看数据库规范化的好时机,例如在维基百科中 https://en.wikipedia.org/wiki/Database_normalization.
我的意思是,Table A 有 5 列。我有一个 SP,我用它从 Table A 中获取 3 列,从 Table B 中获取一列。现在,将 Table B 中的列添加到 [=13 会更好吗? =] A 或使用该 SP 中的子查询从 Table B 中获取该列?
您的问题仍然令人困惑,看起来您还没有理解如何使用关系数据库。那么让我试着解释一下:
假设您有两个 table:
客户端
client_number first_name last_name date_of_birth ...
订单
order_number client_number order_date ...
这是两个独立的table,以便有一个规范化的关系数据库。订单table包含客户编号,因此您可以在客户table中查询客户姓名和出生日期。为了了解客户是否被允许订购某些物品,出生日期可能很重要。但是您不想在每个订单中都存储出生日期 - 它不会改变。
如果你想查询年龄你可以使用子查询:
select
order_number,
order_date,
quantity,
(
select date_of_birth
from client c
where c.client_number = o.client_number
)
from order o
where item = 'whisky';
但大多数时候你会简单地 加入 tables:
select
o.order_number,
o.order_date,
o.quantity,
c.date_of_birth,
c.first_name,
c.last_name
from order o
join client c on c.client_number = o.client_number;
然而,您 不会 更改您的 table 并邀请具有所有问题的冗余,而不必加入。您将数据库设计为结构良好的关系数据库,而不是使您的最新查询易于编写。使用连接和子查询非常非常普遍,必须使用它们通常表明您的数据库构建得很好。
我认为这是你查看数据库规范化的好时机,例如在维基百科中 https://en.wikipedia.org/wiki/Database_normalization.