Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

mysql

I wonder if someone can give me a hand with this...

I need to query two tables where one table contains default data and the second table contains any override data, such as...

TABLE 1

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

TABLE 2

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

I need to return a full set of rows so if table2 text is empty then my result set would contain the table1 text. Likewise if my table2 title is not empty then my result title would be the value of the table2 title thus overriding the default table1 text value.

PERFECT RESULT SET

From the given table structure above

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

I have tried just using a standard join to get all data from both tables and then arranging the data with PHP but I really would like to do it in the SQL if possible.

A roughly example of the query I am running is...

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",

My tables could have up to 6 six columns with the same column names / overriding data. I'd like to keep the default field names intact where possible and avoid assigning new names in the return set, for example

BAD RESULT SET

id = 1
title = 'default title'
override_title = 'this is the override title'
text = 'Hi, default text here...'
like image 675
Mark Avatar asked Apr 15 '13 12:04

Mark


1 Answers

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 ║
╚════╩═══════════════════════════╩═══════════════════════╝
like image 77
John Woo Avatar answered Oct 04 '22 02:10

John Woo