我需要编写自联接查询
我的表是: -
id locid parentid filename
1 1 0 word
2 1 0 excel
3 1 1 power
4 2 0 word
5 2 4 power
我需要使用selfjoin
仅检索parentid = 0的数据
先谢谢
答案 0 :(得分:2)
我不明白为什么你需要一个自我加入,因为你可以通过WHERE
- 条款获得所需的一切:
SELECT
id, locid, parentid, filename
FROM
dbo.YourTable
WHERE
parentid = 0
也许您还想要父记录的所有列:
SELECT
p.id AS ParentID, p.locid AS PlocID, p.parentid AS ParentID, p.filename AS ParentFileName,
c.id, c.locid, c.parentid, c.filename
FROM
dbo.YourTable p
INNER JOIN dbo.YourTable c
ON p.id = c.parentid
WHERE
c.parentid = 0
答案 1 :(得分:2)
我用过这个:
CREATE TABLE my_table(ID NUMBER, locid NUMBER, parentid NUMBER, filename VARCHAR2(10));
BEGIN
INSERT INTO my_table VALUES(1,1,0,'word');
INSERT INTO my_table VALUES(2,1,0,'excel');
INSERT INTO my_table VALUES(3,1,1,'power');
INSERT INTO my_table VALUES(4,2,0,'word');
INSERT INTO my_table VALUES(5,2,4,'power');
END;
/
通常的方法是:
SELECT * FROM my_table;
select * from my_table where parentid=0;
SELECT distinct t1.ID, t1.locid, t1.parentid, t1.filename FROM my_table t1
JOIN my_table t2 ON t1.parentid = t2.parentid AND t2.parentid = 0;
结果如下:
1 1 0 word
2 1 0 excel
4 2 0 word
答案 2 :(得分:1)
根据您的查询,根据您想要使用自联接的不清楚。
无论如何,下面是一个例子,它将给你关于自我加入的清晰画面。
假设Employees是包含与员工相关的数据的表。 员工可以是其他员工的经理,但单身本身则视为任何组织的员工。
〔实施例:
TableName:员工
EmployeeID EmployeeName ManagerID
1 A null
2 B 1
3 C 1
4 D 3
5 E 3
查询:
select e1.EmployeeName as Employee,
e2.EmployeeName as ReportsTo
from employees e1
left outer join employees e2
on e1.ManagerID = e2.EmployeeID
order by e1.EmployeeID
OutPut如下:
Employee Reports To
-------- -----------
B A
C A
D C
E C
答案 3 :(得分:1)
试试这个:
SELECT *.t1
FROM Table1 AS t1
JOIN Table1 t2 ON t1.id = t2.parentid AND t2.parentid = 0
答案 4 :(得分:1)