我有这个表结构:
ProductID ProductName ParentId
13 Test NULL
NULL Test1 14
13 Test2 14
14 Test4 15
NULL Test5 16
现在我想根据Parentid检索结果
请帮我这样做
输出应该是
如果我通过parentid = 14
然后o / p
13 Test2 14
如果我通过parentid = 15
,那么
14 Test4 15
如果我通过parented = 16
,那么
NULL Test5 16
答案 0 :(得分:0)
您可以在CASE
条件中使用WHERE
语句,例如
select ProductID,
ProductName,
ParentId
FROM products
WHERE ISNULL(ProductID,0) = CASE
WHEN ParentId = 14 THEN 13
WHEN ParentId = 15 THEN 14
ELSE 0
END
答案 1 :(得分:0)
根据问题和情节,我假设显示带有ParentID输入参数的记录
SELECT t.* FROM tabletest t
WHERE EXISTS (SELECT t1.ProductId
FROM tabletest t1
WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 14
SELECT t.* FROM tabletest t
WHERE EXISTS (SELECT t1.ProductId
FROM tabletest t1
WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 15
SELECT t.* FROM tabletest t
WHERE EXISTS (SELECT t1.ProductId
FROM tabletest t1
WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 16
我不确定这是否是正确的查询实现,但根据问题,它会切断获取数据的目的。
答案 2 :(得分:0)
可能是这样的
SELECT ProductID,ProductName,ParentId
FROM products
WHERE ProductID IN (SELECT ProductId FROM products WHERE ParentId = 14);
SELECT ProductID,ProductName,ParentId
FROM products
WHERE ProductID IN (SELECT ProductId FROM products WHERE ParentId = 15);
SELECT ProductID,ProductName,ParentId
FROM products
WHERE ISNULL(ProductID,'') IN (SELECT ISNULL(ProductId,'') FROM products WHERE ParentId = 16);