i'm using datatstax jdbc driver.
and i want to execute lookup query like this.
Statement statement = new SimpleStatement("select * from tablename where condition1 = ? and condition2 = ?", value1, value2 );
condition1 is partition key.
and condition2 is part of primary key.
here is my problem.
'value2' can be null. and If 'value2' is null, I want to exclude it from the search condition
Do I have to make two queries per case?
like this?
or is there any way to handle null values?
Statement statement = new SimpleStatement("select * from tablename where condition1 = ? , value1 );
Related
I'm using Jooq to generate SQL
Here is resulting query
insert into MY_TABLE -- I want INSERT INTO(firstField,secondField)
select
?,
?
where not exists (
select 1
from MY_TABLE
where (
firstField = ?
)
)
returning id
MY_TABLE DDL:
create table IF NOT EXISTS MY_TABLE
(
id SERIAL PRIMARY KEY,
firstField int not null,
secondField int not null
)
I can't make Jooq add field names next to insert into MY_TABLE
My builder:
JooqBuilder.default()
.insertInto(table("MY_TABLE"))
.select(
select(
param(classOf[Int]), // 1
param(classOf[Int]), // 2
)
.whereNotExists(select(inline(1))
.from(table("MY_TABLE"))
.where(
DSL.noCondition()
.and(field("firstField", classOf[Long]).eq(0L))
)
)
).returning(field("id")).getSQL
I've tried
.insertInto(table("MY_TABLE"),field("firstField"), field("secondField"))
UPD:
I was confused by compiler exception.
The right solution is
```scala
JooqBuilder.default()
.insertInto(table("MY_TABLE"),
field("firstField",classOf[Int]),
field("secondField",classOf[Int])
)
.select(
select(
param(classOf[Int]),
param(classOf[Int])
)
.whereNotExists(select(inline(1))
.from(table("MY_TABLE"))
.where(
DSL.noCondition()
.and(field("firstField", classOf[Long]).eq(0L))
)
)
).returning(field("id")).getSQL
The thing is that Jooq takes field types from insertInto and doesn't compile if select field types don't match.
I've tried
.insertInto(table("MY_TABLE"),
field("firstField"),
field("secondField")
)
and it didn't compile since no match with
.select(
select(
param(classOf[Int]), // 1
param(classOf[Int]) // 2
)
I've added types to insertInto fields and got match, two ints in insert, two ints in select.
Jooq generated expected query
insert into MY_TABLE -- I want INSERT INTO(firstField,secondField)
select
?,
?
where not exists (
select 1
from MY_TABLE
where (
firstField = ?
)
)
jOOQ just generates exactly the SQL you tell it to generate. You're not listing firstField,secondField in jOOQ, so jOOQ doesn't list them in SQL. To list them in jOOQ, just add:
// ...
.insertInto(table("MY_TABLE"), field("firstField", classOf[Long]), ...)
// ...
Obviously, even without using the code generator, you can reuse expressions by assigning them to local variables:
val t = table("MY_TABLE")
val f1 = field("firstField", classOf[Long])
val f2 = field("secondField", classOf[Long])
And then:
// ...
.insertInto(t, f1, f2)
// ...
Using the code generator
Note that if you were using the code generator, which jOOQ recommends, your query would be much simpler:
ctx.insertInto(MY_TABLE, MY_TABLE.FIRST_FIELD, MY_TABLE.SECOND_FIELD)
.values(v1, v2)
.onDuplicateKeyIgnore()
.returningResult(MY_TABLE.ID)
.fetch();
I would need to write a SQL question based on conditions:
in Condition 1:
SELECT
*
FROM
table_1
WHERE
col_1 IS NULL
AND col_2 IS NOT NULL
and in Condition 2:
SELECT
*
FROM
table_1
WHERE
col_1 IS NULL
How would I be able to achieve this easily in Python? I know I can do filters later on but that's not super efficient as it should be.
The solution used in many tools: Make initial query with dummy TRUE WHERE clause, then depending on conditions can be concatenated with additional filters like this (simplified code):
query = 'select * from table where 1 = 1' # WHERE with dummy TRUE condition
# it can be WHERE TRUE
condition1 = True; # if both conditions are False, query will be without filters
condition2 = True;
filter1='Col1 is not null'
filter2='Col2 is not null'
if condition1:
query = query+' and '+ filter1
if condition2:
query = query+' and '+ filter2
print(query)
Result:
select * from table where 1 = 1 and Col1 is not null and Col2 is not null
More elegant solution using pypika - python query builder. You can build the whole query including table, fields, where filters and joins:
from pypika import Query, Table, Field
table = Table('table')
q = Query.from_(table).select(Field('col1'), Field('col2'))
condition1 = True;
condition2 = True;
if condition1:
q = q.where(
table.col1.notnull()
)
if condition2:
q = q.where(
table.col2.notnull()
)
print(q)
Result:
SELECT "col1","col2" FROM "table" WHERE NOT "col1" IS NULL AND NOT "col2" IS NULL
If i have two table structures, one with:
Let this be A,
PRIMARY KEY (measureid, statename, reportyear, countyname)
and another with, (Let this be B):
PRIMARY KEY ((measureid, statename, reportyear), countyname)
What are the query limitations of table structure B over A ?
In what queries having composite partition key will pose a problem?
In table A where:
PRIMARY KEY (measureid, statename, reportyear, countyname)
You can query the table with just measureid and it will return rows of statename. Specifically:
SELECT FROM ... WHERE measureid = ?
Alternatively, you can also query with:
SELECT FROM ... WHERE measureid = ? AND statename = ?
SELECT FROM ... WHERE measureid = ? AND statename = ? AND reportyear = ?
SELECT FROM ... WHERE measureid = ? AND statename = ? AND reportyear = ? AND countyname = ?
In table B where:
PRIMARY KEY ((measureid, statename, reportyear), countyname)
You must specify all of measureid, statename, reportyear to query the data. This will return all the rows of one partition:
SELECT FROM ... WHERE measureid = ? AND statename = ? AND reportyear = ?
To retrieve one specific row of one partition:
SELECT FROM ... WHERE measureid = ? AND statename = ? AND reportyear = ? AND countyname = ?
To be clear, you cannot query table B with the following:
SELECT FROM ... WHERE measureid = ?
SELECT FROM ... WHERE measureid = ? AND statename = ?
since you must specify the 3 columns of the partition key. I've explained why in this post https://community.datastax.com/questions/7866/. Cheers!
This code results in timeout exception
String City_Code = null;
var result = (from r in myContext.TableA
where ( City_Code == r.City_Code )
select r ).ToList();
while this code will return quickly
String City_Code = null;
var result = (from r in myContext.TableA
where ( r.City_Code == City_Code )
select r ).ToList();
The difference is in the order of operands of the equality. The field City_Code of table TableA is of type nvarchar(20).
What is a possible reason for that???
update: The generated tsql for the 2 queries are identical except for that part: the first one has the condition " #p__linq__2 = [Extent1].[City_Code])" while the second has " [Extent1].[City_Code] = #p__linq__2)"
The value of #p_linq_2 when I notice the time difference is NULL. If I run the queries in ssms with NULL in place of #p_linq_2 they respond both very quickly
Here is a SQL Query I want to convert to EF4.3
command = database.GetSqlStringCommand(#"
select
H.AUTHENTICATION_ID,
USERNAME,
PERMISSIONS,
ORGANIZATION_IDENTIFIER,
O.ORGANIZATION_ID
from
AUTHENTICATION H
left join [AUTHORIZATION] T on H.AUTHENTICATION_ID=T.AUTHENTICATION_ID
join ORGANIZATION O on O.ORGANIZATION_ID = T.ORGANIZATION_ID
order by H.AUTHENTICATION_ID");
Here is the best LINQ I could come up with:
var query = from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
join o in context.Organizations on t.Organizations.OrganizationId equals o.OrganizationId
orderby
h.AuthenticationId
select new
{ AUTHENTICATION_ID = (Int16?)h.AuthenticationId,
h.Username,
t.Permissions,
o.OrganizationIdentifier,
OrganizationID = (Int16?)o.OrganizationId
};
I know i need to merge my first join (between Authorizations & Authentications) into, lets say x and apply DefaultIfEmpty but can't make out the syntax.
EDIT: Image for clarification:
Any help will be highly appreciated. Regards.
The basic syntax for a "left join" in Linq is like this:
from x in table1
join y in table2 on x.id equals y.id into jointable
from z in jointable.DefaultIfEmpty()
select new
{
x.Field1,
x.Field2,
x.Field3,
Field4 = z == null ? 0 : z.Field4
};
In your case, I'm a little confused because the entity relations you seem to be using in your Linq don't match the ones implied by your SQL; are the relationships here zero-or-one, zero-or-many, one-to-one, etc? Specifically, you're doing this:
from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
but your SQL implies that "Authentication" is the parent here with zero-or-more "Authorization" children, not the other way around, which would be more like:
from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
If you can give us a better idea of the data model and what data you expect to get out of it we can more easily explain how that query would look in Linq. Assuming that your relationships match what is implied by the SQL, you should be able to get what you want using the following Linq queries:
var query = from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
select new
{
h.AuthenticationId,
h.Username,
Permissions = t == null ? null : t.Permissions,
Organizations = t == null ? new EntitySet<Organization>() : t.Organizations
};
var query2 = from x in query
from o in x.organizations.DefaultIfEmpty()
select new
{
AUTHENTICATION_ID = (short?)x.AuthenticationId,
x.Username,
x.Permissions,
OrganizationIdentifier = o == null ? null : o.OrganizationIdentifier,
OrganizationID = o == null ? (short?)null : o.OrganizationID
};
Given the foreign keys that exist in the question diagram, how about something like this?
var query = from a in context.Authentications
select new
{
a.AuthenticationID,
a.Username,
a.Authorisations.Permissions ?? false,
a.Authorisations.Organisations.OrganisationIdentifier ?? 0
a.Authorisations.Organisations.OrganisationID ?? 0
};
I went ahead and moved the entire query to a Stored Procedure on the database. This solves the problem by avoiding LINQ and ObjectBuilder in the first place.