加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:23:53 所属栏目:PHP教程 来源:网络整理
导读:我想知道是否有人可以帮助我… 我需要查询两个表,其中一个表包含默认数据,第二个表包含任何覆盖数据,例如… 表格1 id = 5 title = 'This is the default title' text = 'Hi,default text here...' 表2 id = 1 relation_id = 5title = 'This is an override t
我想知道是否有人可以帮助我…

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

表格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

> SQLFiddle Demo

OUTPUT

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读