[英]SQL Server: join one table with two table have same names but select all data from table first if available, otherwise from second table
I tried searching this kind of use case on google but did found exact what i was looking so, Need help to reach to specific point by useful answer, docs or any reference我尝试在谷歌上搜索这种用例,但确实找到了我正在寻找的确切内容,需要通过有用的答案、文档或任何参考来达到特定点
I have this situation: table A has to be joined with table B and table C;我有这种情况:表 A 必须与表 B 和表 C 连接; B and C have similar columns, so there will be duplicate column names in select part, however give preferences to all the data of tables B if available otherwise show data from table c
B 和 C 具有相似的列,因此在 select 部分中会有重复的列名,但是如果可用,请优先考虑表 B 的所有数据,否则显示表 Z4A8A08F09D37B737953649038408B5 中的数据
For example:例如:
SELECT
ae.*, ml.name as name, ml.contact AS contact,
ve.name AS name, ve.contact AS contact
FROM
TABLE ae
LEFT JOIN
TABLE ml ON ae.eid = ml.eid
LEFT JOIN
TABLE ve ON ae.eid = ve.eid
WHERE
ae.eid = 1
ml data毫升数据
eid | name | contact
----+------+--------
1 | xyz | null
ve data数据
eid | name | contact
----+------+--------
1 | xyz | 1
ae data数据
eid | gender
----+--------
1 | male
I want this result:我想要这个结果:
eid | gender | name | contact
----+--------+------+--------
1 | male | xyz | null
But I am getting this for now:但我现在得到这个:
eid | gender | name | contact | contact
----+--------+------+---------+--------
1 | male | xyz | 1 | null
I'm using node-mssql driver for querying SQL Server data.我正在使用 node-mssql 驱动程序来查询 SQL 服务器数据。
Thanks,谢谢,
You must join ve
only if there is no matching row in ml
and you do it if you add in the ON
clause the condition ... AND ml.eid IS NULL
.只有在
ml
中没有匹配的行时才必须加入ve
,并且如果在ON
子句中添加条件... AND ml.eid IS NULL
则必须加入。
Also use COALESCE()
to select the columns from ml
first and if they don't exist from ve
:也使用
COALESCE()
到 select 首先来自ml
的列,如果它们不存在于ve
:
SELECT ae.*,
COALESCE(ml.name, ve.name) AS name,
COALESCE(ml.contact, ve.contact) AS contact
FROM ae
LEFT JOIN ml ON ae.eid = ml.eid
LEFT JOIN ve ON ae.eid = ve.eid AND ml.eid IS NULL
WHERE ae.eid = 1
See the demo .请参阅演示。
Results:结果:
eid![]() |
gender![]() |
name![]() |
contact![]() |
---|---|---|---|
1 ![]() |
male![]() |
xyz ![]() |
null ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.