0

表:

        users: id INT

        items: id INT
               setid INT

         sets: id INT

relationships: userid INT
               itemid INT
               relationship ENUM('owner', 'participant')

给定 auserid和 a setid,我们需要生成集合中所有项目的列表,以及用户与每个项目的关系(如果存在关系)。即结果将

setid    itemid   relationship
---------------------------------
1        1        NULL
1        2        owner
....

以下不起作用,因为第二个where子句消除了relationship为空的行:

select
    sets.id as setid,
    items.id as itemid,
    relatonships.relationship as relationship

from sets
    inner join items on sets.id = items.setid 
    left join relationships on relationships.itemid = items.id

where
    sets.id = 5
    and relationships.userid = 27

但是,第二个where子句会删除该项目与给定用户之间不存在关系的行。如何通过单个查询来完成?

4

2 回答 2

1

这很简单,我不明白你可以在'join ... on'子句中测试一个常量:

select
    sets.setid,
    items.itemid,
    relationships.relationship

from sets
    inner join items on items.setid = sets.id
    left join relationships
        on relationships.itemid = items.id
        and relationships.userid = 5
where
    sets.id = 1
于 2009-11-16T01:36:20.120 回答
0

不是 100% 你在问什么,试试这个

select
    sets.id as setid,
    items.id as itemid,
    relatonships.relationship as relationship

from sets
    inner join items on sets.id = items.event 
    LEFT join relationships on relationships.itemid = items.id

where
    sets.id = [say, 5]
    and relationships.userid = [say, 27]

请记住,如果不存在,则关系列将为 NULL。此外,WHERE 子句中的关系引用也可以消除行。希望这能让你开始,我可能再次误解你想要达到的目标。从您的表格设计来看,用户和集合之间似乎没有关系,您是否可能是表格中的字段列表。

尝试以下查询:

select sets.id as setId,
       items.id as ItemId,
       relationships.relationship
from sets
    join users on 1=1
    join items on sets.id=items.setid
    left join relationships on relationships.itemId = items.id
where 
    sets.id=5 and users.id = 27

通过将 users 表添加到 1=1 的联接中,您根本不需要 where 子句来引用关系表

将左连接更改为:

left join relationships on relationships.itemId = items.id 
AND relationships.userId=users.id
于 2009-11-16T00:29:22.433 回答