HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to get a boolean value into a SELECT operation based on another table?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
booleanintovalueoperationgetanotherbasedhowselecttable

Problem

I have two tables: Message and Attachments (which represent entity types that have a one-to-many relationship) as follows:

CREATE TABLE message (
    messageId ..., 
    [from]..., 
    [to]..., 
    subject..., 
    body...
);

CREATE TABLE attachments (
    messageId..., 
    filename...
);


I want to SELECT the basic message data and include a bit column to denote whether the message has attachments or not. I am trying to use EXISTS in the operation shown below:

SELECT  
M.*,
hasAttachments = EXISTS(SELECT AttachmentId 
                          FROM Attachment 
                         WHERE messageId = M.messageId),
FROM Message M


But this doesn't work - What's the way to do what I'm looking for?

Solution

I'd do it with a CASE statement:

select
    m.*,
    hasAttachments = CASE WHEN EXISTS(select * from Attachment where messageId = M.messageId) then 1 else 0 end
from Message M


or

select distinct 
    m.*,
    hasAttachments = CASE WHEN a.AttachmentId is not null then 1 else 0 end
from Message m
left join Attachment a on a.MessageId = m.MessageId

Code Snippets

select
    m.*,
    hasAttachments = CASE WHEN EXISTS(select * from Attachment where messageId = M.messageId) then 1 else 0 end
from Message M
select distinct 
    m.*,
    hasAttachments = CASE WHEN a.AttachmentId is not null then 1 else 0 end
from Message m
left join Attachment a on a.MessageId = m.MessageId

Context

StackExchange Database Administrators Q#2772, answer score: 7

Revisions (0)

No revisions yet.