从一对多关系中的 SQL 查询中删除重复项
Removing duplicates from SQL query in One to many relationship
我有一个 table 关系如下:
Table 1 -> Table 2(数据库中的一对多关系)
如果我在 table 1:
上执行以下查询
select *
from table1 as t1
where t1.id = 1
我只会从那个 table 中获取特定记录的一条记录,但是如果我加入 table 2,如下所示:
select *
from table1 as t1
join table2 as t2
on t1.id = t2.id
where t1.id=1
这次如果我有ID from table 1 inserted in table 2,我会得到多条记录。 this join in query, in one to many relationship??
有人可以帮我解决这个问题吗??谢谢!
我使用了 koppinjo 的方式,查询现在如下所示:
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY PC.SubCategoryID
ORDER BY PC.[SubCategoryID] ) AS [Row]
,sc.*
,pc.MeasurementQuantity
,pc.Price
,pc.ProductCategoryID
,pc.ProductID
,p.Dimensions
,p.FileName
,p.ProductDescription
,p.ProductName
,mu.Unit
FROM SubCategory AS sc
JOIN ProductsCategories AS pc ON sc.SubCategoryID = pc.SubCategoryID
JOIN Products AS p ON p.ProductID = pc.ProductID
JOIN MeasurementUnits AS mu
ON mu.MeasurementUnitID = p.MeasurementUnitID
WHERE pc.SubCategoryID = 1
) AS t
WHERE t.[Row] = 1
现在的问题是,查询returns只有1个结果。但是,如果同一类别下有两种产品怎么办?
P.S。我忘了提到这个查询的实际数据库模式是:
产品 -> 产品类别 <- 类别
假设 2 个产品属于两个类别,我需要同时获取这两个产品,但不要重复。 Koppinjo 的方式 returns 只有 1 个结果...
我建议使用 window 函数,例如 ROW_NUMBER()。例如:
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t2.[primary/unique key]) AS [row]
,t1.*
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
WHERE t1.id = 1
) t
WHERE t.[row] = 1
像这样的事情应该能让你找到正确的方向。希望对您有所帮助!
您可以使用 distinct 并且不显示 table2 中的任何列。类似于:
select distinct t1.*
from table1 as t1
join table2 as t2
on t1.id = t2.id
where t1.id=1
我有一个 table 关系如下:
Table 1 -> Table 2(数据库中的一对多关系)
如果我在 table 1:
上执行以下查询select *
from table1 as t1
where t1.id = 1
我只会从那个 table 中获取特定记录的一条记录,但是如果我加入 table 2,如下所示:
select *
from table1 as t1
join table2 as t2
on t1.id = t2.id
where t1.id=1
这次如果我有ID from table 1 inserted in table 2,我会得到多条记录。 this join in query, in one to many relationship??
有人可以帮我解决这个问题吗??谢谢!
我使用了 koppinjo 的方式,查询现在如下所示:
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY PC.SubCategoryID
ORDER BY PC.[SubCategoryID] ) AS [Row]
,sc.*
,pc.MeasurementQuantity
,pc.Price
,pc.ProductCategoryID
,pc.ProductID
,p.Dimensions
,p.FileName
,p.ProductDescription
,p.ProductName
,mu.Unit
FROM SubCategory AS sc
JOIN ProductsCategories AS pc ON sc.SubCategoryID = pc.SubCategoryID
JOIN Products AS p ON p.ProductID = pc.ProductID
JOIN MeasurementUnits AS mu
ON mu.MeasurementUnitID = p.MeasurementUnitID
WHERE pc.SubCategoryID = 1
) AS t
WHERE t.[Row] = 1
现在的问题是,查询returns只有1个结果。但是,如果同一类别下有两种产品怎么办?
P.S。我忘了提到这个查询的实际数据库模式是:
产品 -> 产品类别 <- 类别
假设 2 个产品属于两个类别,我需要同时获取这两个产品,但不要重复。 Koppinjo 的方式 returns 只有 1 个结果...
我建议使用 window 函数,例如 ROW_NUMBER()。例如:
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t2.[primary/unique key]) AS [row]
,t1.*
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
WHERE t1.id = 1
) t
WHERE t.[row] = 1
像这样的事情应该能让你找到正确的方向。希望对您有所帮助!
您可以使用 distinct 并且不显示 table2 中的任何列。类似于:
select distinct t1.*
from table1 as t1
join table2 as t2
on t1.id = t2.id
where t1.id=1