我想知道是否有人可以帮助我...
我需要查询两个表,其中一个表包含默认数据,第二个表包含任何覆盖数据,例如...
id = 5
title = 'This is the default title'
text = 'Hi, default text here...'
Run Code Online (Sandbox Code Playgroud)
id = 1
relation_id = 5
title = 'This is an override title'
text = NULL
Run Code Online (Sandbox Code Playgroud)
我需要返回一整套行,所以如果table2文本为空,那么我的结果集将包含table1文本.同样,如果我的table2标题不为空,那么我的结果标题将是table2标题的值,从而覆盖默认的table1文本值.
从上面给出的表结构
id = 5
title = 'This is an override title'
text = 'Hi, default text here...'
Run Code Online (Sandbox Code Playgroud)
我曾尝试使用标准连接从两个表中获取所有数据,然后使用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",
Run Code Online (Sandbox Code Playgroud)
我的表最多可以有6列,具有相同的列名/覆盖数据.我希望尽可能保持默认字段名称不变,并避免在返回集中指定新名称
id = 1
title = 'default title'
override_title = 'this is the override title'
text = 'Hi, default text here...'
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
OUTPUT
??????????????????????????????????????????????????????????
? ID ? TITLE ? TEXT ?
??????????????????????????????????????????????????????????
? 5 ? This is an override title ? Hi. default text here ?
??????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2183 次 |
| 最近记录: |