[英]SQL Select from 2 tables with same column names only return column when not null
我想知道是否有人可以帮我解决这个问题...
我需要查询两个表,其中一个表包含默认数据,第二个表包含任何覆盖数据,例如...
id = 5
title = 'This is the default title'
text = 'Hi, default text here...'
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.