SQL 服务器:加入一个 table 和两个 table 具有相同名称但 select 所有数据来自 table 第一个如果可用,否则来自第二个 table

SQL Server: join one table with two table have same names but select all data from table first if available, otherwise from second table

我尝试在 google 上搜索这种用例,但确实找到了我想要的东西,需要帮助通过有用的答案、文档或任何参考来达到特定点

我有这种情况:table A 必须与 table B 和 table C 连接; B 和 C 有相似的列,所以 select 部分会有重复的列名,但是优先选择 tables B 的所有数据,否则显示来自 table c[ 的数据=22=]

例如:

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

毫升数据

eid | name | contact
----+------+--------
1   | xyz  | null

有数据

eid | name | contact
----+------+--------
1   | xyz  | 1

ae 数据

eid | gender
----+--------
1   | male

我想要这个结果:

eid | gender | name | contact
----+--------+------+--------
1   | male   | xyz  | null

但我现在得到这个:

eid | gender | name | contact | contact
----+--------+------+---------+--------
1   | male   | xyz  | 1       | null

我正在使用 node-mssql 驱动程序查询 SQL 服务器数据。

谢谢,

只有在 ml 中没有匹配的行时才必须加入 ve,并且如果在 ON 子句中添加条件 ... AND ml.eid IS NULL,则可以加入 ve。 =26=] 还首先使用 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

参见demo
结果:

eid gender name contact
1 male xyz null