我必须得到A.Ref_id,B.Ref_id和B_Id的Ref_id
Table A_B having Column_A_ID and Column_B_ID
Table A having ID, Ref_id, Name, B_Id (This is the B.ID from table B)
Table B having ID, Ref_id, Name
目前我正在进行以下查询
SELECT A.Ref_id as A_Ref_Id, B.Ref_id as B_Ref_Id, B_Id
FROM A_B
JOIN A on A_B.Column_A_ID = A.Id
JOIN B on A_B.Column_B_ID = B.Id
JOIN B AS Main_B on B.id = A.B_id;
通过此查询,我正确地显示了A.Ref_Id
和B.Ref_Id
列,因为它们显示了相关的Ref_id
,但对于B_Id
我想要{{1}而且它显示Ref_id
而不是。
答案 0 :(得分:0)
到目前为止,我看到上次联接的ON
条件必须使用表B
的别名:
SELECT A.Ref_id as A_Ref_Id, B.Ref_id as B_Ref_Id, B_Id
FROM A_B
JOIN A on A_B.Column_A_ID = A.Id
JOIN B on A_B.Column_B_ID = B.Id
JOIN B AS Main_B on Main_B.id = A.B_id;
顺便说一句,在sqlFiddle中有一些例子可能会更有帮助
答案 1 :(得分:0)
您想要这个(对吗?):B.Ref_id
行中B.ID = A.B_Id
的值,而此行依次为A.ID=A_B.Column_A_ID
。以及A_B
中每一行的全部内容:
SELECT A.Ref_id as A_Ref_id, B.Ref_id as B_Ref_id, Main_B.Ref_id
FROM A_B
JOIN A ON A_B.Column_A_ID = A.Id
JOIN B ON A_B.Column_B_ID = B.Id
JOIN B AS Main_B on Main_B.id = A.B_id;
(@Mojtaba提出的重要修正的最后一行代码)