有一张表格式如下
A
id name fatherid .............
1 a 0
2 b 0
3 c 0
4 d 2
5 e 2
6 f 3 问我给出id=4时
如何得出
2 b 0
4 d 2 我不想用这种方法得出
select a1.* from A a1,B b2 where (a1.id = b2.fatherid or a1.id = b2.id) and a.id = 4 group by
a1.id,a1.name,a1.fatherid
因为group by 要group 所有的字段,我如有50个字段就难了
请问有好的方法吗
A
id name fatherid .............
1 a 0
2 b 0
3 c 0
4 d 2
5 e 2
6 f 3 问我给出id=4时
如何得出
2 b 0
4 d 2 我不想用这种方法得出
select a1.* from A a1,B b2 where (a1.id = b2.fatherid or a1.id = b2.id) and a.id = 4 group by
a1.id,a1.name,a1.fatherid
因为group by 要group 所有的字段,我如有50个字段就难了
请问有好的方法吗
解决方案 »
- 如何实现这个查询...
- 请问本机SERVER2000 连不上是怎么回事?在线等
- 求SQL语句或存储过程。。。。。。。。。。。。。
- 恢復BAK報錯
- 急!!各位帮忙一下,我要导一个数据库中的表到另一数据库中的表里面。
- 求一简单SQL语句
- SQL Report Builder Filter Question.
- 安装MYSQL installer-community-5.6.10.1,出现的错误,怎么解决
- 我的SQL Server 不能创建数据库了,发生错误:1807 未能获得数据库 'model' 上的排它锁。请稍后重试操作。
- How To: 在Linked Server中,动态指定要打开的Excel文件名? 在线等候。
- 根据给定的两个日期 insert 记录!!谢谢!!!
- 请教一个关于sql server的作业的问题,请各位大侠指教~!
insert @tb
SELECT 1, 'a', 0 UNION ALL
SELECT 2, 'b', 0 UNION ALL
SELECT 3, 'c', 0 UNION ALL
SELECT 4, 'd', 2 UNION ALL
SELECT 5, 'e', 2 UNION ALL
SELECT 6, 'f', 3select * from @tb where id<=4 and id%2=0
/*
id name fatherid
----------- ---- -----------
2 b 0
4 d 2
*/
as
(
select * from A where id=4
union all
select t.* from A t join cte c on t.id=c.fatherid
)
select * from cte
RETURNS @t_Level TABLE(ID char(3),Level int)
AS
BEGIN
DECLARE @Level int
SET @Level=1
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.PID,@Level
FROM tb a,@t_Level b
WHERE a.ID=b.ID
AND b.Level=@Level-1
END
RETURN
END
GO
--上面的用户定义函数可以处理一个节点有多个父节点的情况,对于标准的树形数据而言,由于每个节点仅有一个父节点,所以也可以通过下面的用户定义函数实现查找标准树形数据的父节点。
CREATE FUNCTION f_Pid(@ID char(3))
RETURNS @t_Level TABLE(ID char(3))
AS
BEGIN
INSERT @t_Level SELECT @ID
SELECT @ID=PID FROM tb
WHERE ID=@ID
AND PID IS NOT NULL
WHILE @@ROWCOUNT>0
BEGIN
INSERT @t_Level SELECT @ID
SELECT @ID=PID FROM tb
WHERE ID=@ID
AND PID IS NOT NULL
END
RETURN
END
while @fatherid<>0
select id,name,@fatherid=fatherid from id=@fatherid
declare @A table (id int,name varchar(1),fatherid int)
insert into @A
select 1,'a',0 union all
select 2,'b',0 union all
select 3,'c',0 union all
select 4,'d',2 union all
select 5,'e',2 union all
select 6,'f',3declare @id int
set @id=4
select * from @A a where id=@id or exists(select 1 from @a where a.id=fatherid and id=@id)
-- Author: happyflsytone
-- Date:2008-10-20 17:36:41
-------------------------------------- Test Data: ta
IF OBJECT_ID('ta') IS NOT NULL
DROP TABLE ta
Go
CREATE TABLE ta(id INT,name NVARCHAR(1),fatherid NVARCHAR(1))
Go
INSERT INTO ta
SELECT 1,'a','0' UNION ALL
SELECT 2,'b','0' UNION ALL
SELECT 3,'c','0' UNION ALL
SELECT 4,'d','2' UNION ALL
SELECT 5,'e','2' UNION ALL
SELECT 6,'f','3'
GO
--Start
;with t
as(
select * from ta where id = 4
union all
select ta.* from ta ,t where t.fatherid = ta.id
)
SELECT *
FROM t--Result:
/*id name fatherid
----------- ---- --------
4 d 2
2 b 0(2 行受影响)
*/
--End