![](/img/trans.png)
[英]SQL - All values from first table joined with first value from second one and null otherwise
[英]SQL Server: join one table with two table have same names but select all data from table first if available, otherwise from second table
我嘗試在谷歌上搜索這種用例,但確實找到了我正在尋找的確切內容,需要通過有用的答案、文檔或任何參考來達到特定點
我有這種情況:表 A 必須與表 B 和表 C 連接; B 和 C 具有相似的列,因此在 select 部分中會有重復的列名,但是如果可用,請優先考慮表 B 的所有數據,否則顯示表 Z4A8A08F09D37B737953649038408B5 中的數據
例如:
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
數據
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
則必須加入。
也使用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
請參閱演示。
結果:
開齋節 | 性別 | 姓名 | 接觸 |
---|---|---|---|
1 | 男性 | xyz | null |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.