簡體   English   中英

SQL Select from 2 個具有相同列名的表僅在不為空時返回列

[英]SQL Select from 2 tables with same column names only return column when not null

我想知道是否有人可以幫我解決這個問題...

我需要查詢兩個表,其中一個表包含默認數據,第二個表包含任何覆蓋數據,例如...

表格1

id = 5  
title = 'This is the default title'  
text = 'Hi, default text here...'  

表2

id = 1  
relation_id = 5
title = 'This is an override title'  
text = NULL

我需要返回一組完整的行,因此如果 table2 文本為空,那么我的結果集將包含 table1 文本。 同樣,如果我的 table2 標題不為空,那么我的結果標題將是 table2 標題的值,從而覆蓋默認的 table1 文本值。

完美的結果集

從上面給定的表結構

id = 5
title = 'This is an override title'
text = 'Hi, default text here...'

我曾嘗試僅使用標准連接從兩個表中獲取所有數據,然后使用 PHP 排列數據,但如果可能的話,我真的很想在 SQL 中進行。

我正在運行的查詢的粗略示例是...

SELECT vt.id, 
  vt.title as vt_title,
  vt.text AS vt_text,
  vt.relation_id,
  t.id, t.title,
  t.text 
  FROM table1 vt 
  LEFT JOIN table2 t ON vt.relation_id = $id 
  AND vt.relation_id = t.id",

我的表最多可以有 6 個具有相同列名/覆蓋數據的六列。 例如,我想盡可能保持默認字段名稱不變,並避免在返回集中分配新名稱

糟糕的結果集

id = 1
title = 'default title'
override_title = 'this is the override title'
text = 'Hi, default text here...'
SELECT  a.ID,
        COALESCE(b.Title, a.Title) Title,
        COALESCE(b.Text, a.Text) Text
FROM    Table1 a
        LEFT JOIN Table2 b
            ON a.ID = b.relation_ID

輸出

╔════╦═══════════════════════════╦═══════════════════════╗
║ ID ║           TITLE           ║         TEXT          ║
╠════╬═══════════════════════════╬═══════════════════════╣
║  5 ║ This is an override title ║ Hi. default text here ║
╚════╩═══════════════════════════╩═══════════════════════╝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM