0

我使用 SQL-Server 2008 并有以下表格。

用户

用户身份
1
2
3

对象

对象ID | 类别
9 | 一个
8 | 乙
7 | 一个
6 | C

用户对象

用户名 | 对象标识
1 | 9
3 | 7
3 | 6

如您所见,userobjects 是一个链接表。不幸的是,它缺少一些条目。我可以将它们包含在脚本中,但我想知道 sql 中是否有解决方案。

对于属于类别“A”的每个用户 ID 和每个对象 ID,用户对象中都应该有一个条目。所以我想要的是这样的:

用户名 | 对象标识
1 | 9
1 | 7
2 | 9
2 | 7
3 | 9
3 | 7
3 | 6
4

2 回答 2

1

I could include them with a script but I wonder if there is a solution in sql.

This is a select query using UNION (here is SQL-DEMO);

select u.userId, o.objectId
from objects o cross join users u
where o.category = 'A'
union
select u.userId, o.objectId
from users u join userobjects uj on u.userid = uj.userId
     join objects o on uj.objectid = o.objectid
where o.category <> 'A'
order by u.userid,o.objectid desc

--RESULTS
userId  objectId
1       9
1       7
2       9
2       7
3       9
3       7
3       6
于 2013-01-23T15:24:28.480 回答
0

You can do it without a UNION using a LEFT join and a non-traditional INNER JOIN to objects

SELECT DISTINCT u.userid, 
                o.objectid 
FROM   users u 
       LEFT JOIN userobjects uj 
              ON u.userid = uj.userid 
       INNER JOIN objects o 
               ON uj.objectid = o.objectid 
                   OR ( o.category = 'A' ) 
ORDER  BY u.userid, 
          o.objectid DESC 

Fiddle

于 2013-01-23T15:30:03.803 回答