Sql:从两个表中选择数据而不重复第一个表值?

时间:2013-04-10 12:16:41

标签: sql sql-server model-view-controller linq-to-sql foreign-key-relationship

CREATE TABLE [dbo].[test](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[ctext] [varchar](12) NOT NULL,
 CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
(
[id] ASC
))

CREATE TABLE [dbo].[Comments](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[cComments] [varchar](250) NOT NULL,
[fk_test] [bigint] NOT NULL)
GO

ALTER TABLE [dbo].[Comments]  WITH CHECK ADD  CONSTRAINT [FK_Comments_test] FOREIGN KEY([fk_test])
REFERENCES [dbo].[test] ([id])
ON DELETE CASCADE

两个表与正常的一对多关系链接。

我想要一个返回列表列表的选择:

-----------------------------------------------------
|test.id|test.cnumber|comments.id|comments.cComments|
|-------|------------|-----------|------------------|
| 1     | mytest1    |     1     |   comment1       |
|       |            |     2     |   comment2       |
|       |            |     3     |   comment3       |
|       |            |     4     |   comment4       |
|       |            |     5     |   comment5       |
|       |            |     6     |   comment6       |
| 2     | mytest2    |     7     |   comment7       |
|       |            |     8     |   comment8       |
| 3     | mytest3    |     7     |   comment9       |
-----------------------------------------------------

无论如何都要去做吗?

我试图用sql存储过程替换linq。

1 个答案:

答案 0 :(得分:2)

试试这个解决方案 -

DECLARE @test TABLE 
(
  [id] [bigint] IDENTITY(1,1) NOT NULL
, [ctext] [varchar](12) NOT NULL
)

DECLARE @Comments TABLE
(
[id] [bigint] IDENTITY(1,1) NOT NULL,
[cComments] [varchar](250) NOT NULL,
[fk_test] [bigint] NOT NULL
)


INSERT INTO @test (ctext)
VALUES ('1'), ('2')

INSERT INTO @Comments (cComments, fk_test)
VALUES ('123', 1), ('123', 1), ('123', 2), ('123', 2)

SELECT  id = CASE WHEN d.rcount = 1 THEN d.id END
, cnumber = CASE WHEN d.rcount = 1 THEN d.cnumber  END
, d.commentid
, d.cComments
FROM (
SELECT 
   t.id
 , cnumber = t.ctext
 , commentid = c.id
 , c.cComments
 , rcount = ROW_NUMBER() OVER (PARTITION BY t.[id] ORDER BY t.[id] DESC)
FROM @test t
JOIN @Comments c ON t.id = c.fk_test
) d