我的SQL Server中有三个表
1。)注册它的列
Reg_Id bigint, primary key and auto increment
Name nvarchar(50),
Tranx_id nvarchar(30),
Email nvarchar(30),
Username nvarchar(30),
Password nvarchar(30),
Edition_Id nvarchar(50),
Default_Id nvarchar(50),
Reg_Date datetime,
usertype nvarchar(50),
2。)AllEditionPages它的列
Page_id bigint, primary key and auto increment
edition_date datetime,
noofpages int,
Page_no int,
image_path nvarchar(50),
Active int,
type_of_page varchar(50),
Image_Width int,
Image_Height int,
3。)版
id int, primary key and auto increment
edition_date datetime,
noofpages int,
XMLFile nvarchar(50),
PDFFile nvarchar(50),
PDFPrefix nvarchar(50),
type nvarchar(50),
price nvarchar(50),
reg_req nvarchar(50)
如上表所示,我尝试下面的SQL查询
SELECT edi.*, aep.*, reg.*
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
从这个查询我得到这个输出:
id edition_date type price page-id
96 2012-07-18 00:00:00.000 free null 2503
96 2012-07-18 00:00:00.000 free null 2503
我输出两行,但只想输出
中的单行答案 0 :(得分:1)
您可以通过以下方式在此方案中使用common table expression
:
WITH cteTable AS
(
SELECT edi.*, aep.*, reg.*
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
)
select top 1 * from cteTable
由于您的两个表包含edition_date,您需要指定列名而不是使用“*”,如下所示:
WITH cteTable AS
(
SELECT edi.id,edi.edition_date,edi.noofpagez,edi.XMLFile,edi.PDFFile ,edi.PDFPrefix,edi.type,edi.price,edi.reg_req ,
aep.Page_id, aep.edition_date,aep.noofpages,aep.Page_no,aep.image_path,aep.Active,aep.type_of_page,aep.Image_Width,aep.Image_Height,
reg.Reg_Id,reg.Name,reg.Tranx_id,reg.Email,reg.Username,reg.Password,reg.Edition_Id,reg.Default_Id,reg.Reg_Date,reg.usertype
FROM Edition as edi INNER JOIN Registration as reg
ON edi.id = reg.Edition_Id INNER JOIN AllEditionPages as aep
ON edi.edition_date = aep.edition_date
where reg.Edition_Id= edi.id
and reg.Reg_ID = 14
)
select top 1 * from cteTable
答案 1 :(得分:0)
如果2行具有相同的值,您可以使用select distinct,或者您可以在查询后面使用LIMIT 0,1
。
答案 2 :(得分:0)
您必须指定一行。从您的putput看起来您有重复的数据,如果这是问题,您应该使用distinct来获取不同的行。否则指定您需要的内容。