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...
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
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.
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
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
OUTPUT
╔════╦═══════════════════════════╦═══════════════════════╗
║ ID ║ TITLE ║ TEXT ║
╠════╬═══════════════════════════╬═══════════════════════╣
║ 5 ║ This is an override title ║ Hi. default text here ║
╚════╩═══════════════════════════╩═══════════════════════╝
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With