snippetsqlMinor
How to get a boolean value into a SELECT operation based on another table?
Viewed 0 times
booleanintovalueoperationgetanotherbasedhowselecttable
Problem
I have two tables:
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:
But this doesn't work - What's the way to do what I'm looking for?
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 MBut this doesn't work - What's the way to do what I'm looking for?
Solution
I'd do it with a CASE statement:
or
select
m.*,
hasAttachments = CASE WHEN EXISTS(select * from Attachment where messageId = M.messageId) then 1 else 0 end
from Message Mor
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.MessageIdCode Snippets
select
m.*,
hasAttachments = CASE WHEN EXISTS(select * from Attachment where messageId = M.messageId) then 1 else 0 end
from Message Mselect 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.MessageIdContext
StackExchange Database Administrators Q#2772, answer score: 7
Revisions (0)
No revisions yet.