我有一个小问题需要回答。 有4个表称为
user : uid, uname
category: cid,canme
product : pid, pname
assemble : aid, uid,pid,cid;
我想显示产品表中的记录,但需求是pid(来自产品),而uid(来自用户)不应该一次出现在同一行的汇编表中。
答案 0 :(得分:0)
我相信这是你正在寻找的:
select * from user u, product p, assemble a where p.pid not in
(Select pid from assemble) and u.uid not in (select uid from assemble)
答案 1 :(得分:0)
查看this SQL Fiddle及其中的评论。您在这里涵盖了很多概念,并且您想要考虑您的设计以及您想要完成的任务,但要解决您在问题中提出的目标:
pid
和{{ 1}}要在汇编表中复制,所以我把它作为主键)。我的陈述非常直白:需求是pid(来自产品)和uid(来自用户) 不应该出现 一次在同一行的汇编表中。 (强调我的)
您可以使用JOINS将不同表格中的项目相互关联。实际上,汇编表通常被称为"连接表"。我的例子是使用内连接(意思是,值必须存在于两个表中)。
您可以使用FOREIGN KEYS确保要在其他表中引用的列存在。
以下是SQL Fiddle行为不端的代码。
创建并填充表格:
cid
查询:
CREATE TABLE users (
uid serial,
uname text,
CONSTRAINT user_pkey PRIMARY KEY (uid)
);
CREATE TABLE categories (
cid serial,
cname text,
CONSTRAINT cat_pkey PRIMARY KEY (cid)
);
CREATE TABLE products (
pid serial,
pname text,
CONSTRAINT prod_pkey PRIMARY KEY (pid)
);
CREATE TABLE assemble (
join_id serial,
uid bigint,
pid bigint,
cid bigint,
CONSTRAINT assemble_pkey PRIMARY KEY (uid, pid),
CONSTRAINT assemble_user_fkey FOREIGN KEY (uid)
REFERENCES users (uid),
CONSTRAINT assemble_prod_fkey FOREIGN KEY (pid)
REFERENCES products (pid),
CONSTRAINT assemble_cat_fkey FOREIGN KEY (cid)
REFERENCES categories (cid)
);
INSERT INTO users (uname) VALUES ('Akshay');
INSERT INTO users (uname) VALUES ('Mom');
INSERT INTO users (uname) VALUES ('Dad');
INSERT INTO categories (cname) VALUES ('Shoes');
INSERT INTO categories (cname) VALUES ('Hats');
INSERT INTO categories (cname) VALUES ('Coats');
INSERT INTO products (pname) VALUES ('Blue Suede Nikes');
INSERT INTO products (pname) VALUES ('Fedora');
INSERT INTO products (pname) VALUES ('Flying Jacket');
-- Give Akshay a hat
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Akshay'),
(SELECT cid FROM categories WHERE cname='Hats'),
(SELECT pid FROM products WHERE pname='Fedora')
);
-- Give Mom a coat
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Mom'),
(SELECT cid FROM categories WHERE cname='Coats'),
(SELECT pid FROM products WHERE pname='Flying Jacket')
);
-- Give Dad some shoes
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Dad'),
(SELECT cid FROM categories WHERE cname='Shoes'),
(SELECT pid FROM products WHERE pname='Blue Suede Nikes')
);