鉴于我们在MS Access中有3个表,
表1
ID MyName Months
111 A 1
222 B 1
333 F 2
444 D 2
555 G 3
666 C 3
表2
ID Income Months
111 500 1
222 900 1
333 800 2
444 6000 2
表3
ID Income Months
555 65656 3
666 77777 3
我想将表2和表3加入到表1中,以便我的回归 Table_Result
ID NAME Income Months
111 A 500 1
222 B 900 1
333 F 800 2
444 D 6000 2
555 G 65656 3
666 C 77777 3
如何获取Table_Result?
答案 0 :(得分:1)
只需将UNION
与LEFT JOIN
一起使用时,您就不必使用Nz
:
SELECT T1.ID,T1.MyName as Name, Nz(T2.Income,T3.Income) as Income,T1.Months
FROM Table1 T1 LEFT JOIN
Table2 T2 ON T1.ID=T2.ID LEFT JOIN
Table3 T3 ON T1.ID=T3.ID
ORDER BY T1.ID
<强>解释强>
如果第一个参数是Nz
,则 null
函数返回第二个参数。阅读更多here。
<强>结果:强>
ID MyName Income Months
111 A 500 1
222 B 900 1
333 F 800 2
444 D 6000 2
555 G 65656 3
666 C 77777 3
mysql SQL fiddle中的示例结果(使用coalesce
表示mysql而不是Nz
)
答案 1 :(得分:0)
尝试此查询
select a.id,a.Myname,b.income,a.month
from table1 a
join table2 b on a.id=b.id
union all
select a.id,a.Myname,c.income,a.month
from table1 a
join table3 c on c.id=a.id
答案 2 :(得分:0)
您需要UNION
table2和table3,然后将它们加入table1:
SELECT table1.*, table4.income FROM table1 LEFT JOIN
(SELECT * FROM table2 UNION SELECT * FROM table3) as table4
ON table4.Months = table1.Months AND table4.ID = table1.ID
您首先UNION
table2和table3将其所有内容合并为一个“table4”,您只需在匹配的JOIN
和{{1}上执行Months
}。如果你真的不需要它,你最终可能想要删除ID
的条件。
或者,您可以通过执行Months
答案 3 :(得分:0)
SELECT A.ID, A.MYNAME, A.MONTHS, B.INCOME
FROM Table1 AS A
INNER JOIN (SELECT * FROM Table2 UNION SELECT * FROM Table3) AS B ON B.ID = A.ID
答案 4 :(得分:-1)
您可以使用sql UNION
运算符从2个或更多表中获取单个记录集
SELECT ID, Income, Months FROM table2
UNION
SELECT ID, Income, Months FROM table3;
使用UNION
解决您的问题的方法是:
Select t1.ID, t1.MyName, Table_Result.Income, t1.Months
from Table1 t1
join (SELECT ID, Income, Months FROM table2
UNION
SELECT ID, Income, Months FROM table3) as Table_Result on Table_Result.id = t1.id;
如果您想要所有(重复的)值,您可以使用ALL
运算符的UNION
修饰符
Select t1.ID, t1.MyName, Table_Result.Income, t1.Months
from Table1 t1
join (SELECT ID, Income, Months FROM table2
UNION ALL
SELECT ID, Income, Months FROM table3) as Table_Result on Table_Result.id = t1.id;
这是最后一个例子的sql fiddle