如何从带有外键的2个FB SQL表中进行选择?

时间:2017-10-24 16:06:37

标签: sql select foreign-keys firebird

我创建了2个如下表格:

create table accounts(
accountOID int primary key not null,
bankcodenumber int,
accountnumber int
);

create table user(
userOID int primary key not null,
name varchar(25),
accountOID0 int,
accountOID1 int
);

每个用户都有1个或2个帐户,因此要声明外键我输入:

alter table user add foreign key(accountOID0) references account(accountOID);

alter table user add foreign key(accountOID1) references account(accountOID);

现在,我如何列出这样的帐户:

Name    | Bankcodenumber | Accountnumber
Sanchez | 0123456789     | 547
Trent   | 1234567890     | 278
Sanchez | 2345678901     | 480
Carlson | 3435577890     | 503
Jackson | 6833556904     | 168
...     | ...            | ...

我试过这个但没有成功:

select name, (select bankcodenumber, accountnumber from account
where user.accountOID0 = accountOID or user.accountOID1 = accountOID)
from user order by name;

3 个答案:

答案 0 :(得分:2)

您似乎想要union all

select u.name, a.Bankcodenumber, a.Accountnumber
from user u join
     account a
     on u.accountoid0 = a.accountoid
union all
select u.name, a.Bankcodenumber, a.Accountnumber
from user u join
     account a
     on u.accountoid1 = a.accountoid;

答案 1 :(得分:2)

SELECT u.name,
       a.bankcodenumber,
       a.accountnumber 
  FROM user u
INNER JOIN 
       accounts a
    ON u.accountOID0 = a.accountOID
UNION
SELECT u.name,
       a.bankcodenumber,
       a.accountnumber 
  FROM user u
INNER JOIN 
       accounts a
    ON u.accountOID1 = a.accountOID; 

答案 2 :(得分:1)

没有UNION但使用带有联接的单个SELECT的选项:

http://sqlfiddle.com/#!5/17ccc/1/0

select
   Coalesce(u1.name, u0.name) as name1,
   a.bankcodenumber,
   a.accountnumber
 from accounts a
   left join users u0
     on u0.accountOID0 = a.accountOID
   left join users u1
     on u1.accountOID1 = a.accountOID
 where name1 is not null

它使用以

形式输入的topicstarter示例数据
create table accounts(
accountOID int primary key not null,
bankcodenumber int,
accountnumber int
);

create table users(
userOID int primary key not null,
name varchar(25),
accountOID0 int references accounts(accountOID),
accountOID1 int references accounts(accountOID)
);

insert into accounts values (1, 0123456789, 547);
insert into accounts values (2, 1234567890, 278);
insert into accounts values (3, 2345678901, 480);
insert into accounts values (4, 3435577890, 503);
insert into accounts values (5, 6833556904, 168);

insert into users values(1, 'Trent', NULL, 2);
insert into users values(2, 'Carlson', 4, NULL);
insert into users values(3, 'Sanchez', 3, 1);
insert into users values(4, 'Jackson', 5, NULL);

如果有一个用户的accountOID0等同于另一个用户的accountOID1,则可能会丢失一些数据。但主题起始者暗示不应该有这样的情况。虽然他也没有说是否有一些限制或其他警卫来确保永远不会发生。