SQL从具有相同列名的2个表中选择仅在非空时返回列

时间:2013-04-15 12:11:12

标签: php mysql sql

我想知道是否有人可以帮我一把......

我需要查询两个表,其中一个表包含默认数据,第二个表包含任何覆盖数据,例如......

表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列,列名相同/覆盖数据相同。 我希望尽可能保持默认字段名称不变,并避免在返回集中指定新名称,例如

BAD RESULT SET

id = 1
title = 'default title'
override_title = 'this is the override title'
text = 'Hi, default text here...'

1 个答案:

答案 0 :(得分:5)

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 ║
╚════╩═══════════════════════════╩═══════════════════════╝