如何在postgresql中编写查询? (关系多对多)

时间:2016-07-08 07:02:31

标签: postgresql

我还是个新手。 我创建了这样的db:

DROP DATABASE IF EXISTS image_store_db;
CREATE DATABASE image_store_db;

\c image_store_db;

CREATE TABLE categories_images (
    categories_images_id SERIAL PRIMARY KEY,
    title VARCHAR NOT NULL,
    image_url VARCHAR NOT NULL,
    design_url VARCHAR NOT NULL
);

CREATE TABLE images (
    images_id SERIAL PRIMARY KEY,
    title VARCHAR NOT NULL,
    rating REAL NOT NULL,
    image_url VARCHAR NOT NULL,
    desc_short TEXT NOT NULL,
    desc_full TEXT NOT NULL
);

CREATE TABLE ref_categories_images (
    categories_images_id integer REFERENCES categories_images (categories_images_id) ON UPDATE CASCADE,
    images_id integer REFERENCES images (images_id) ON UPDATE CASCADE ON DELETE CASCADE,
    CONSTRAINT ref_categories_images_pkey PRIMARY KEY (images_id, categories_images_id)
);

INSERT INTO categories_images(title, image_url, design_url)
    VALUES ('SIMPLE TITLE TEST', '/TEST_URL.PNG', '/TEST_URL.PNG');

INSERT INTO images(title, rating, image_url, desc_short, desc_full)
    VALUES ('SIMPLE TITLE TEST', 4.5, '/TEST_URL.PNG', 'TEST_SHORT', 'TEST_FULL');

请帮助。教我,怎么写一个查询:插入(对于图像类别)和选择(图像来自类别ID)等... 请...

1 个答案:

答案 0 :(得分:0)

我的回答假设categories_images是类别表,images是图像表。表和属性名称似乎表明,多对多连接的概念尚不清楚;我会调用三个表categoryimagecategory_image_map

对于INSERT:如果您的问题是serial主键,请使用INSERT ... RETURNING
您可以在一个语句中插入所有三个表:

WITH im(im_id) AS (
        INSERT INTO categories_images ...
           RETURNING categories_images_id
     ),
     cat(cat_id) AS (
        INSERT INTO images ...
           RETURNING images_id
     )
INSERT INTO ref_categories_images (categories_images_id, images_id)
   VALUES ((SELECT cat_id FROM cat), (SELECT im_id FROM im));

对于查询,您只需加入三个表:

SELECT ...
FROM categories_images c
     JOIN ref_categories_images r
        ON r.categories_images_id = c.categories_images_id
     JOIN images i
        ON r.images_id = i.images_id

并为您的条件添加WHERE子句,例如

WHERE c.categories_images_id = 42

WHERE i.image_title = 'Mona Lisa'