Search code examples
t-sqlsql-server-2017

Return values from left join only if it exists, otherwise from the main table


I have 2 tables

CREATE TABLE [dbo].[Owners]
(
    [OwnerId] [int] NOT NULL,
    [AccessToken] [nvarchar](50) NULL,
    [TokenSecret] [nvarchar](50) NULL
)

CREATE TABLE [dbo].[Tweets]
(
    [TweetId] [int] IDENTITY(1,1) NOT NULL, 
    [ReferenceId] [int] NULL,
    [TweetContent] [nvarchar](max) NULL,
    [ReferenceType] [int] NOT NULL,
    [AccessToken] [nvarchar](50) NULL,
    [TokenSecret] [nvarchar](50) NULL,
)

I would like to return all fields of tweets, and based on if there is an owners for the tweet, the AccessToken/TokenSecret will come from the owner table, if not then it will come from the tweets table.

I am having a hard time figuring out the best/efficient way to write this query.

This is what I have so far (only returns from main table, not owner if there is one)

SELECT *  
FROM Tweets t
LEFT JOIN Owners o ON t.ReferenceId = o.OwnerId
WHERE t.ReferenceType = 1

I am using SQL Server 2017, in the tweet table, ReferenceId is the ownerid correspondence to he tweets table


Solution

  • Perhaps coalesce would be helpful to select the first non-null value:

    select coalesce(o.AccessToken, t.AccessToken) as actualAccessToken [...]