简体   繁体   English

带Union子句的简单Oracle SQL查询

[英]Simple Oracle SQL query with Union clause

is it possible to write SQL query to retrieve the names of person with animals named 'roxy'? 是否可以编写SQL查询来检索动物名为“ roxy”的人的名字? If so please tell me how to write the query. 如果是这样,请告诉我如何编写查询。 I don't know Oracle so I'm confused of this foreign key with reference. 我不了解Oracle,因此我对该外键与参考混淆了。

Also, shouldn't we add an index for person_id otherwise it will create a speed issue later on when doing union? 另外,我们是否不应该为person_id添加索引,否则稍后进行联合时会产生速度问题? How to write the query to add that index? 如何编写查询以添加该索引? or does the reference create the index as well? 还是引用也创建索引?

  create table person (
    person_id   integer,
    name        varchar(50)
  );

  create table animal(
    owner_id    integer,
    name        varchar(50),
    foreign key (owner_id) references person (person_id)
  );

Oracle uses just the same syntax for joins than SQL Server. Oracle对联接使用与SQL Server相同的语法。

select * from person p inner join animal a on p.person_id = a.owner_id

Also, you should set primary keys on your tables, and put an index on them. 另外,您应该在表上设置主键,并在它们上放置索引。

Left Join are used when you wish to obtain ALL elements from the "left" table, even if they dont have a match on the joining table. 当您希望从“左”表中获得所有元素时,即使它们在联接表上没有匹配项,也可以使用左联接。

On oracle you would create a primary key as follows: 在oracle上,您将创建一个主键,如下所示:

CREATE UNIQUE INDEX XPKperson ON person(person_id)

You can use the below query, 您可以使用以下查询,

SELECT p.name
FROM   person p,
       animal a
WHERE  p.person_id = a.owner_id
AND    a.name = 'roxy';

You should create a primary keys on tables as it uniquely defines a record. 您应该在表上创建主键,因为它唯一地定义了一条记录。

Syntax to create an index, 创建索引的语法,

CREATE INDEX index_name ON TABLE_NAME(column_name);

Refer this link to understand more about creating an index. 请参考此链接以了解有关创建索引的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM