我有一个包含三列的规格主表
(
ID BIGINT PRIMARY KEY,
Name varchar,
Value varchar
)
包含两列的产品主表
(
ID BIGINT PRIMARY KEY,
Name varchar
)
带有
的股票表(
StockID BIGINT PRIMARY KEY,
ProductID BIGINT FOREIGN KEY (Product.ID),
SpecGroupID BIGINT UNIQUE KEY,
Stock INT
)
带
的规范分组表(
GroupID BIGINT FOREIGN KEY (Stock.SpecGroupID),
SPecificationID BIGINT FOREIGN KEY (Specification.ID),
PRIMARY KEY (Composite)
)
现在我正在寻找规格的组合,如果它有任何股票。 但无法找到匹配精确组合的逻辑。
如果规范组合的n规范与规范分组表中的stock.SpecGroupID相关联,那么我面临的问题。 虽然我搜索的数量少于那些n规格组合,但它总是为n specs组返回相同的SpecGroupID。
想象一下,我有一个苹果(颜色:红色;尺寸:5;重量:10) 有人订购苹果(颜色:红色;尺寸:5)
我需要给出结果:不可用
答案 0 :(得分:0)
这对你有用吗?
SELECT Specification.ID SpecId
, Specification.Name SpecificationName
, Value SpecificationValue
, MAX(ISNULL(Stock.Stock,0)) HasStock
FROM
Specification
LEFT JOIN SpecificationGrouping sg
ON sg.SpecificationID = Specification.ID
LEFT JOIN Stock
ON GroupID = SpecGroupID
GROUP BY Specification.ID
, Specification.Name
, Value
答案 1 :(得分:0)
Groups
告诉我每个小组的规格。GroupDetail
加入一个字符串中的所有属性,例如Color|Red,Size|5,Weight|10
OrderDetail
只是测试输入。在这个样本6和9中是订单。<强> SQL Fiddle Demo 强>
WITH Groups as
(
SELECT *
FROM SpecificationGrouping SG
INNER JOIN Specification S
ON Sg.SPecificationID = S.ID
),
GroupDetail as
(
Select distinct ST2.GroupID,
substring(
(
Select ','+ ST1.Name + '|' + ST1.Value AS [text()]
From Groups ST1
Where ST1.GroupID = ST2.GroupID
ORDER BY ST1.Name
For XML PATH ('')
), 2, 1000) [Detail]
From Groups ST2
),
OrderDetail as
(
SELECT Detail
FROM GroupDetail
WHERE GroupID = 9
)
SELECT S.SpecGroupID, S.Stock, G.[Detail]
FROM Stock S
INNER JOIN GroupDetail G
ON S.SpecGroupID = G.GroupID
RIGHT JOIN OrderDetail O
ON O.Detail = G.Detail
输出为9
| SpecGroupID | Stock | Detail |
|-------------|-------|----------------------------|
| 3 | 5 | Color|Red,Size|5,Weight|10 |