如何关联表SQL

时间:2018-06-19 13:40:03

标签: sql join

我有三个表,我想将它们关联起来,但是我不知道我在做什么错。如果我的思维方式不好,你也可以纠正我吗?

我的客户表的主键为ID_c列,

create table clients
(
  id_c    INTEGER not null,
  name    VARCHAR2(20),
  age     INTEGER,
  address VARCHAR2(20),
  Primary key (id_c)
);

我也有主键为ID_p列的产品。

create table PRODUCTS
(
  id_p              NUMBER not null,
  name_product      VARCHAR2(30),
  price             NUMBER,
  duration          NUMBER,
  primary key (id_p)
);

现在我创建第三个

create table TRANSACTIONS
(
  id_t NUMBER not null,
  id_c NUMBER not null,
  id_p NUMBER not null
  primary key (ID_t),
  foreign key (ID_c) references CLIENTS (ID_c),
  foreign key (ID_p) references PRODUCTS (ID_p)
);

现在我想查看所有已连接的记录,所以我试图使用它:

select * from transactions join clients using (id_c) and join products using (id_p);

但只有行之有效的

select * from transactions join clients using (id_c);

是关系数据库还是即时通讯使事情变得太容易了,太原始了?我该怎么做才能连接一切?

3 个答案:

答案 0 :(得分:1)

您只是想加入吗?

    select * from transactions a 
join clients b on a.id_c = b.id_c
join products c on a.id_p = c.id_p

答案 1 :(得分:1)

尝试

select * 
from transactions 
    inner join clients on transactions.id_c = clients.id_c
    inner join products on transactions.id_p = products.id_p;

答案 2 :(得分:1)

如果要联接3个表,只需编写:

SELECT * FROM TRANSACTIONS t JOIN client c on t.id_c = c.id_c JOIN PRODUCTS p on t.id_p = p.id_p