querybuilder icon indicating copy to clipboard operation
querybuilder copied to clipboard

How to do "SELECT EXISTS(SELECT 1 FROM ...)"?

Open Bobsans opened this issue 3 years ago • 3 comments

Maybe need to add method query.AsExists() or any other for do this?

Bobsans avatar Oct 06 '22 22:10 Bobsans

image

Can some of these help you? Or you can always use a raw querie

nielslucas avatar Nov 28 '22 13:11 nielslucas

These are methods for adding conditions. For example .HavingExists(...) will generate SELECT ... FROM ... HAVING EXISTS(...). And .WhereExists(...) will generate SELECT ... WHERE EXISTS(...). The Query class has a .AsCount() method that generates SELECT COUNT(*) FROM .... My question is how to generate exactly SELECT EXISTS(...) Maybe add a method like .AsExists() that will generate a query that will have SELECT EXISTS(...) in the view?

Bobsans avatar Nov 29 '22 15:11 Bobsans

I am looking for something similar, but in my case it is:

select
    case when exists (select * from sessions where user_id = u.id) then 1 else 0 end is_current
from users u

So I am literally would like to include any query into the raw query, like:

query.SelectRawFormat("case when exists {0} then 1 else 0 end is_current", sub_query)

So the approach could be more flexible, eg:

query.SelectRawFormat("case when exists {0} then ? when exists {1} then ? else 0 end is_current", 
    formats: new object[] { sub_query1, sub_query2 },
    bindings: new object[] { 1, 2 })

as a current workaround is:

select
    case when s.user_id is not null then 1 else 0 end is_current
from users u
    left join (select user_id from sessions group by user_id) s on s.user_id = u.id

fairking avatar Mar 14 '23 12:03 fairking