当没有直接设置外键时,我在连接两个表时遇到了一些问题。
我有两张桌子:
表A
{A.ID} {A.NAME} {Parentid} {A_FK} (foreign key)
A.ID1 A.NAME1 NULL A_FK1
A.ID2 A.NAME2 NULL A_FK2
A.ID3 A.NAME3 A.ID2 NULL
A.ID4 A.NAME4 NULL A.FK4
OtherA OtherId Other Other
表B
{B.ID} {B.Code}
A.FK1 some_text1
A.FK2 some_text2
A.FK4 some_text3
B.ID1 some_text4
在表A中.A.ID3没有FK但它的ParentID指向具有ForeingKey的A.ID2。
我希望:
{A.ID} {A.NAME} {B.Code}
A.ID1 A.NAME1 some_text1
A.ID2 A.NAME2 some_text2
A.ID3 A.NAME3 some_text2
A.ID4 A.NAME4 some_text3
任何人都可以帮助我加入此活动吗?
答案 0 :(得分:0)
试试这段代码,这是正常的
SELECT TABLEA.ID,TABLEA.NAME,TABLEB.Code
FROM TABLEA
INNER JOIN TABLEB
ON TABLEA.ID=TABLEB.ID OR TABLEA.Parentid=TABLEB.ID;
答案 1 :(得分:0)
您可以首先使用TableB
和FK
将所有行加入UNION ALL
,并使用TableA
将ParentID
上的行加入:{ / p>
示例数据
CREATE TABLE TableA(
ID INT,
Name VARCHAR(10),
ParentID INT NULL,
FK INT NULL
)
CREATE TABLE TableB(
ID INT,
Code VARCHAR(50)
)
INSERT INTO TableA VALUES
(1, 'Name1', NULL, 1),
(2, 'Name2', NULL, 2),
(3, 'Name3', 2, NULL),
(4, 'Name4', NULL, 4);
INSERT INTO TableB VALUES
(1, 'Some Text 1'),
(2, 'Some Text 2'),
(4, 'Some Text 3');
<强> QUERY 强>
SELECT
a.ID, a.Name, b.Code
FROM TableA a
INNER JOIN TableB b ON a.FK = b.ID
WHERE a.ParentID IS NULL
UNION ALL
SELECT
a1.ID, a1.Name, b.Code
FROM TableA a1
INNER JOIN TableA a2 ON a2.ID = a1.ParentID
INNER JOIN TableB b ON a2.FK = b.ID
WHERE a1.FK IS NULL
ORDER BY ID
<强> RESULT 强>
ID Name Code
----------- ---------- -------------------
1 Name1 Some Text 1
2 Name2 Some Text 2
3 Name3 Some Text 2
4 Name4 Some Text 3
答案 2 :(得分:0)
如果您的父子关系可以是多个级别,那么您需要编写这样的递归查询:
CREATE TABLE TableA(ID INT, Name VARCHAR(10), ParentID INT NULL, FK INT NULL );
CREATE TABLE TableB( ID INT, Code VARCHAR(50));
INSERT INTO TableA VALUES (1, 'Name1', NULL, 1);
INSERT INTO TableA VALUES (2, 'Name2', NULL, 2);
INSERT INTO TableA VALUES (3, 'Name3', 2, NULL);
INSERT INTO TableA VALUES (4, 'Name4', NULL, 4);
INSERT INTO TableA VALUES (5, 'Name4', 3, NULL);
INSERT INTO TableB VALUES (1, 'Some Text 1');
INSERT INTO TableB VALUES (2, 'Some Text 2');
INSERT INTO TableB VALUES (4, 'Some Text 3');
WITH X (ID, NAME, FK) AS (
SELECT ID, NAME, FK
FROM TABLEA
WHERE PARENTID IS NULL
UNION ALL
SELECT T.ID, T.NAME, X.FK
FROM TABLEA T
INNER JOIN X ON (T.PARENTID = X.ID)
)
SELECT X.ID, X.NAME , TABLEB.CODE
FROM X INNER JOIN TABLEB ON (X.FK = TABLEB.ID);