SQL-Query加入两个表

时间:2016-10-25 10:09:14

标签: sql postgresql postgresql-9.4

我在SQL上打破了我的大脑,也许有人可以给我一个提示。

示例设置:

CREATE TABLE album
(
  name text NOT NULL,
  id serial NOT NULL,
  user_id bigint NOT NULL
);

CREATE TABLE album_share
(
  id integer NOT NULL,
  user_id bigint NOT NULL,
  album_id bigint NOT NULL,
  permission character varying(20)
 );

INSERT INTO album_share VALUES (21, 23, 8, 'OWNER');
--INSERT INTO album_share VALUES (22, 22, 8, 'READ');

INSERT INTO album VALUES ('album1', 8, 23);
INSERT INTO album VALUES ('album2', 12, 23);
INSERT INTO album VALUES ('album3', 13, 22);
INSERT INTO album VALUES ('album4', 15, 22);



--Expecting with user_id=23
-- album1,album2
--!! Failed: album1 is not in the result !!

SELECT * from album a 
LEFT JOIN album_share share ON share.album_id = a.id 
where (a.user_id = 23 or share.user_id = 23)  
  and (share.permission is null or share.permission != 'OWNER');

--Expecting with user_id=22
-- album3,album4
-- Works fine

SELECT * from album a 
LEFT JOIN album_share share ON share.album_id = a.id 
where (a.user_id = 22 or share.user_id = 22)  
  and (share.permission is null or share.permission != 'OWNER');

该示例也可在线获取:http://rextester.com/DCD25332

我正在尝试从两个表中选择加入并按其数据过滤。在小提琴中更好地解释。用user_id = 23的第一个查询没有选择相册,我认为是因为过滤,但我无法解决。

4 个答案:

答案 0 :(得分:1)

第一个查询不返回album1行,因为关联的album_share.permissionOWNER,因为它不满足条件permission IS NULL OR permission != 'OWNER'而被过滤掉。< / p>

答案 1 :(得分:0)

album1 album_share 表有关系,并且&#39; share.permission为空&#39;在这种情况下条件永远不会成真。

如下所示进行更改

SELECT * from album a 
LEFT JOIN album_share share ON share.album_id = a.id 
where (a.user_id = 23 or share.user_id = 23 or share.permission != 'OWNER');

答案 2 :(得分:0)

这不是因为你说你不想要它,请看这里:

  

share.permission!=&#39;所有者&#39;

这与分享权利不是“所有者”时的情况相同。 如果你想对对方说“&#39; =&#39;而不是&#39;!=&#39;。

- 期待user_id = 23 - album1,album2 - !失败:album1不在结果!!

SELECT *来自专辑a LEFT JOIN album_share share ON share.album_id = a.id其中(a.user_id = 23或share.user_id = 23)和(share.permission为null或share.permission!=&#39; OWNER&#39;); < / p>

答案 3 :(得分:0)

如果您执行以下查询,您将获得2条记录。

   SELECT * from album a 
   LEFT JOIN album_share share 
   ON share.album_id = a.id 
   where (a.user_id = 23 or share.user_id = 23);

Output

然后当你在where子句中添加第二个条件时,它会过滤一条记录。我不知道你是否真的要检查它的权限是否不等于OWNER。如果你想要两个记录,那么你将不得不修改第二个查询,你的查询将如下所示:

SELECT * from album a 
LEFT JOIN album_share share 
ON share.album_id = a.id 
where (a.user_id = 23 or share.user_id = 23)
and (share.permission is null or share.permission = 'OWNER');

<强>输出:

Output

您的查询:

SELECT * from album a 
LEFT JOIN album_share share 
ON share.album_id = a.id 
where (a.user_id = 23 or share.user_id = 23)
and (share.permission is null or share.permission != 'OWNER');

<强>输出:

Output-3