Запросить другие поля в таблицах, на которые ссылается FK в соединительной таблице - PullRequest
1 голос
/ 18 февраля 2020

У меня есть таблица «junction» (recipe_ingredients), которую я использую для обработки отношения «многие ко многим» в моей базе данных. Каждое поле в этой таблице является ссылкой на PK другой таблицы: recipe_id, ingredient_id, quantity_id и measure_id. Это PK таблиц metadata, ingredients, quantities и measurements. За исключением таблицы metadata, во всех этих таблицах есть только два поля: PK и имя или номер, связанные с этим PK.

Я пытаюсь запросить recipe_ingredients для всех строк, которые иметь заданный recipe_id ... но вместо отображения PK в каждой строке с этим recipe_id я хочу отобразить имя / номер, связанный с этим PK, в этой таблице.

Так что вместо запрос, который возвращает это:

recipe_id | ingredient_id | quantity_id | measure_id
----------+---------------+-------------+-----------
1         | 10            | 2           | 3
----------+---------------+-------------+-----------
1         | 12            | 2           | 3
----------+---------------+-------------+-----------
1         | 13            | 5           | 6
----------+---------------+-------------+-----------
...

Я ищу запрос, который возвращает что-то вроде этого:

recipe_id | ingredient_name | quantity_num | measure_num
----------+-----------------+--------------+------------
1         | Ground cayenne  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Ground paprika  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Olive oil       | 1            | tbsp
----------+-----------------+--------------+------------
...

Я только начал изучать SQL, поэтому я знаю только как сделать простые запросы к одной таблице. Я даже не знаю, с чего начать этот запрос, за исключением того, что мне может понадобиться что-то вроде join. Какой запрос я могу написать для достижения этой цели?

Я использую sqlite3 в Debian.

recipe_ingredients таблица "junction":

CREATE TABLE recipe_ingredients (
    recipe_id               int,
    ingredient_id           int,
    quantity_id             int,
    measure_id              int,
    primary key (recipe_id, ingredient_id),
    foreign key (recipe_id)
            references metadata (recipe_id)
                    on update restrict
                    on delete restrict,
    foreign key (ingredient_id)
            references ingredients (ingredient_id)
                    on update restrict
                    on delete restrict,
    foreign key (quantity_id)
            references quantities (quantity_id)
                    on update restrict
                    on delete restrict,
    foreign key (measure_id)
            references measurements (measure_id)
                    on update restrict
                    on delete restrict
);

Это внешние таблицы, на которые ссылается таблица соединений:

create table if not exists ingredients (
    ingredient_id           integer         primary key,
    ingredient_name         text            not null
);

create table if not exists quantities (
    quantity_id             integer         primary key,
    quantity_num            int             not null
);

create table if not exists measurements (
    measure_id              integer         primary key,
    measure_name            text            not null
);

create table if not exists metadata (
    recipe_id               integer         primary key,
    recipe_name             text            not null,
    course_id               int,
    cuisine_id              int,
    servings                int,
    prep_time               int,
    cook_time               int,
    total_time              int,
    foreign key (course_id)
            references courses (course_id)
                    on update restrict
                    on delete restrict,
    foreign key (cuisine_id)
            references cuisine (cuisine_id)
                    on update cascade
                    on delete cascade
);

1 Ответ

1 голос
/ 18 февраля 2020

Вы можете join соединительную таблицу с каждой из связанных таблиц, например:

select
    ri.recipe_id,
    i.ingredient_name,
    q.quantity_num,
    m.measure_num
from recipe_ingredients ri
inner join ingredients i  on i.ingredient_id = ri.ingredient_id
inner join quantities q   on q.quantity_id = ri.quantity_id
inner noin measurements m on m.measure_id = ri.measure_id
where ri.recipe_id = ?

Знак вопроса (?) обозначает recipe_id, который вы ищете.

...