SQL Server 2008 - 使用额外列“HasMutual”创建视图

时间:2011-11-25 02:57:42

标签: sql sql-server select view

我正在尝试使用SQL Server 2008创建一个View,它可以让我查看用户a和b是否有共同的朋友。

使用a和b存储在名为Friendships的表中作为发件人和收件人,其中IsPending列表示友情是否已被收件人批准。

无论如何,主表是这样的:

Sender | Recipient | IsPending
(Stored on a single row.)

如何创建一个视图,返回一个名为HasMutual的额外列,如果为false则为0,如果为true,则为1?

感谢。

2 个答案:

答案 0 :(得分:1)

我希望自己能够聪明地弄清楚这个问题!

我无法相信前两个答案都得到了投票。而且这并不像Ben Thul声称的那样微不足道!

由于单个查询难以解决,您会考虑采用不同的方法吗?

接受一对用户的存储过程怎么样,然后列出他们的共同朋友?

(我假设IsPending = 1表示他们还不是朋友)

CREATE PROCEDURE find_mutual_friends
(
  @user1 varchar(255),
  @user2 varchar(255)
)
as 
SELECT
  Friends
FROM
(SELECT
  Friendships.Sender as Friends
FROM
  Friendships
WHERE
  Friendships.Recipient = @user1
  and Friendships.IsPending = 0
UNION ALL
SELECT
  Friendships.Recipient as Friends
FROM
  Friendships
WHERE
  Friendships.Sender = @user1
  and Friendships.IsPending = 0) FriendsTempTable
WHERE
  FriendsTempTable.Friends in
(SELECT
  Friendships.Sender as Friends
FROM
  Friendships
WHERE
  Friendships.Recipient = @user2
  and Friendships.IsPending = 0
UNION ALL
SELECT
  Friendships.Recipient as Friends
FROM
  Friendships
WHERE
  Friendships.Sender = @user2
  and Friendships.IsPending = 0)

答案 1 :(得分:0)

CREATE VIEW ViewName
AS

SELECT
        Sender , Recipient , IsPending, IsPending AS HasMutual
FROM    myTable