0

这个数据库查询有什么问题

select 
    abstract_author.name, 
    title, 
    affiliation_number,
    af_name 
from        
    abs_affiliation_name, 
    abstract_affiliation,
    abstracts_item,
    abstract_author,
    authors_abstract 
where 
    abstracts_item._id = authors_abstract.abstractsitem_id and  
    abstract_author._id = authors_abstract.abstractauthor_id and 
    abstract_affiliation._id = abstract_author._id and  
    abs_affiliation_name._id =  abstracts_item._id 

我得到了我的预期结果。但是,有人说这不是推荐的方式或好的做法。你能告诉我写我的查询的推荐方法是什么(我的意思是哪个有连接)?

4

3 回答 3

1

不建议在 where 子句中进行连接。相反,最好使用显式的 JOIN 条件。所以你的查询是

SELECT
  abstract_author.name
, title
, affiliation_number
, af_name 
FROM abstracts_item
JOIN authors_abstract ON abstracts_item._id = authors_abstract.abstractsitem_id
JOIN abstract_author ON abtract_author.id = authors_abstract.abstractauthor_id
JOIN abstract_affiliation ON abstract_affiliation._id = abstract_author._id
JOIN abs_affiliation_name ON abs_affiliation_name._id = abstracts_item.id

我强烈建议您在表上使用别名,因为这样可以避免混淆。在此示例中,如果您将标题字段引入其他表之一,则查询很可能会中断,因为它知道要定位哪个表。我会做类似的事情

SELECT
  au.name
, af.title
, af.affiliation_number
, af.af_name 
FROM abstracts_item ai
JOIN authors_abstract aa ON ai._id = aa.abstractsitem_id
JOIN abstract_author au ON au.id = aa.abstractauthor_id
JOIN abstract_affiliation af ON af._id = au._id
JOIN abs_affiliation_name an ON an._id = ai.id

您需要更改选择位中的别名,因为我已经猜到它们来自哪些表

于 2013-08-01T09:34:08.503 回答
0

不,您的查询没有任何问题。这是个人喜好,您使用的 ANSI-89 隐式连接已经过时了 20 多年,它们在 ANSI-92 中被替换为显式 JOIN 语法。

Aaron Bertrand写了一篇引人入胜的文章,说明为什么在大多数情况下最好使用较新的连接语法,以及使用 ANSI-89 连接的潜在缺陷。在大多数在这种情况下,两种方法的执行计划将完全相同(假设您没有意外地与隐式连接交叉连接)。值得注意的是,有时 Oracle 会产生不同的执行计划,而 ANSI-89 连接语法可以产生两者中更有效的一种。(我已经看到了一个针对我的答案而发布的示例,但目前我找不到它,您现在必须相信我的话)。但是,我不会将此作为始终使用 ANSI-89 连接的理由,使用 ANSI-92 连接语法的另一个关键原因是可以使用 ANSI 语法实现外连接,而隐式连接的外连接语法因 DBMS 而异.

例如在甲骨文上

SELECT  *
FROM    a, b
WHERE   a.id = b.id(+)

在 SQL-Server 上(已弃用)

SELECT *
FROM    a, b
WHERE   a.id *= b.id

但是,以下两者都适用:

SELECT  *
FROM    a
        LEFT JOIN b
            ON a.id = b.id

如果您总是使用显式连接,您最终会得到更一致(在我看来更具可读性)的查询。

于 2013-08-01T09:54:15.357 回答
0

我建议您使用joins 和aliases如下

select aath.name, /*alias*/title, /*alias*/affiliation_number,/*alias*/af_name 
from abs_affiliation_name aan
join abstracts_item ai on aan._id =  ai._id     
join abstract_affiliation aa on  aa._id = aath._id 
join authors_abstract  aAbs on ai._id = aAbs.abstractsitem_id 
join abstract_author aath on aath._id = aAbs.abstractauthor_id 
于 2013-08-01T09:33:05.967 回答