sqlkata / querybuilder

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird
https://sqlkata.com
MIT License
3.08k stars 498 forks source link

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

Open Bobsans opened 1 year ago

Bobsans commented 1 year ago

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

nielslucas commented 1 year ago

image

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

Bobsans commented 1 year ago

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?

fairking commented 1 year ago

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