2
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 

兩個表與一個正常的一對多關係鏈接。Sql:從兩個表中選擇數據而不重複第一個表值?

我想選擇返回一個列表的列表:

----------------------------------------------------- 
|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。

+4

也許你應該這樣做在應用層。在oracle中 – 2013-04-10 12:17:36

+0

,你會用一個LAG函數 – Randy 2013-04-10 12:35:13

+0

哪個SQL Server版本? 2012還支持'lag()'函數。 – 2013-04-10 12:44:08

回答

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 
+0

@MFFuzzyButton - 評論2有一個無效的fk_test,即您的設置是錯誤的。 – muhmud 2013-04-10 13:01:50

+0

@Mr模糊按鈕我寫了一個表變量,只是作爲例子。在user1958148的問題中描述了表之間的外鍵。因此,你描述的情況永遠不會發生。 – Devart 2013-04-10 13:15:36