在给定第三个 map/join table 中的值的情况下,从 2 table 中检索值

Retrieve values from 2 tables given a value in a third map/join table

我有 table lawyers:

CREATE TABLE lawyers (
  id SERIAL PRIMARY KEY,
  name VARCHAR,
  name_url VARCHAR,
  pic_url VARCHAR(200)
);

想象一下整个 table 看起来像这样:

table firms:

CREATE TABLE firms (
  id SERIAL PRIMARY KEY,
  name VARCHAR,
  address JSONb
);

整个table:

然后为了映射多对多关系,我正在使用映射 table lawyers_firms:

CREATE TABLE lawyers_firms (
  lawyer_id INTEGER,
  firm_id INTEGER
 );

我不确定如何从 lawyersfirms 给定 lawyers_firms.firm_id.

检索值

例如:

1. SELECT name, name_url and pic_url FROM lawyers. 
2. also SELECT name and address FROM firms.
3. WHERE `lawyers_firms.firm_id` = 1.

试试这个:

SELECT l.name, l.name_url, l.pic_url, f.name, f.address 
FROM lawyers l
 inner join lawyers_firms lf
 on lf.lawyer_id = l.id 
 inner join firms f
 on f.id = lf.firm_id
 WHERE lf.firm_id = 1;