从表中选择两个一对多表中仅与另一个表中的一个值相连的值

时间:2017-01-01 18:08:44

标签: java sqlite

作为表结构的一个例子:

CREATE TABLE group (group_id int primary key, group_name string unique)
CREATE TABLE gitems (gitem_id int primary key, ...)
CREATE TABLE group_gitem (group_id int foreign key, gitem_id int foreign key)
CREATE TABLE object_gitem (gitem_id int foreign key, object_id string foreign key)
CREATE TABLE object (object_id string primary key, ...)

我想选择出现在一个特定组中的所有object_ids,而不是出现在多个组中的object_ids。我尝试了以下查询,但它没有做我希望的事情,实际上什么也没有返回。

SELECT object_id, COUNT(group_id) AS link_count FROM group 
LEFT JOIN group_gitem ON group_gitem.group_id = group.group_id 
LEFT JOIN object_gitem ON object_gitem.gitem_id = group_gitem.gitem_id 
GROUP BY object_id 
HAVING link_count <= 1 AND group_id = 0

我打算使用object_ids删除磁盘上各自的jpg图像,例如aBjf9k4d9l.jpg将链接到object_id值aBjf9k4d9l。然后我计划删除该组和所有相关项目,同时保留仍然链接到另一个组的对象,即使它存在于我计划从数据库中删除的那个组中。

1 个答案:

答案 0 :(得分:1)

使用set操作通常比连接更简单:

WITH og AS (
  SELECT object_id,
         group_id
  FROM object_gitem
  JOIN group_gitem USING (gitem_id)
)
SELECT object_id
FROM object
WHERE object_id     IN (SELECT object_id
                        FROM og
                        WHERE group_id =  0)
  AND object_id NOT IN (SELECT object_id
                        FROM og
                        WHERE group_id <> 0);