Getting different results from Spring JPA query vs raw SQL in console - mysql

I have the following SQL query which returns one result, as expected, when I run it in the MySQL console:
SELECT DISTINCT a.* FROM account a
INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE '%test#test.com%'
OR a.id IN (SELECT e.accountId FROM environment e WHERE e.externalId LIKE '%test#test.com%'
OR e.name LIKE '%test#test.com%')
OR c.email = 'test#test.com'
I use the same query in my application code, yet zero results are returned:
#Query(value = "SELECT DISTINCT a.* FROM account a INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE %?1% OR a.id IN " +
"(SELECT e.accountId FROM environment e WHERE e.externalId LIKE %?1% OR e.name LIKE %?1%) " +
"OR c.email = ?1", nativeQuery = true)
List<Account> findAccountByKeyword(String keyword);
I see the following SQL being generated, which looks fine to me:
select distinct account0_.id as id1_0_, account0_.createdBy as createdB2_0_, account0_.createdDate as createdD3_0_, account0_.lastUpdatedBy as lastUpda4_0_, account0_.updatedDate as updatedD5_0_, account0_.accountName as accountN6_0_, account0_.globalMessage as globalMe7_0_, account0_.isConsultingPartner as isConsul8_0_, account0_.isNonProfit as isNonPro9_0_, account0_.isSuspended as isSuspe10_0_, account0_.note as note11_0_, account0_.parentId as parentI12_0_, account0_.products as product13_0_, account0_.salesforceId as salesfo14_0_, account0_.type as type15_0_, account0_.typeShort as typeSho16_0_, account0_.usedProducts as usedPro17_0_
from account account0_ inner join contact contact1_ on (account0_.id=contact1_.accountId)
where account0_.accountName like ? or account0_.id in (select environmen2_.accountId from environment environmen2_ where environmen2_.externalId like ?
or environmen2_.name like ?)
or contact1_.email=?
Any ideas what could be going wrong here? I have verified that the value of keyword is correct so I'm at a complete loss what else I can try. Other questions regarding inconsistencies between native SQL and queries within Spring are all talking about problems with date types but I'm not even using dates here or anything dialect-specific.
Please let me know if you need more information and I will edit my question accordingly.

are your queries really the same? Like '%test#test.com%' in your Mysql and LIKE %?1% in your native SQL. I guess you lose the % before and after your parameters somewhere.
Replacing like %?1% with like CONCAT('%', ?1, '%') might be the solution

Related

Consults with subqueries and use of regexp

I am trying to identify users that can receive medicines produce interactions. For that I have used this code:
SELECT c.user, COUNT(DISTINCT c.user)
FROM mytable AS c
JOIN (SELECT id_beneficiario, mes
FROM mytable
WHERE codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03|
L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08|
N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03') AS d
ON c.user = d.user AND c.mes = d.mes
WHERE (c.codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03|
L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08|
N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03')
GROUP BY c.user;
I am working local and the consult take too much time and apper the next Error: Error code: 2013. Lost conection to MYSQL server during query. Would be possible optimize my code to avoid the error?
Can this work for you?
WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09',
'N05AH02','L01XE06','R06AA02','A03FA03','L04AA27',
'J02AC01','N06AB03','C03CA01','N05AD01', etc)
This IN clause will return true if codigo_atc matches any of the values in the (list).
SQL is far better at set logic than it is at regular expression matching.
You can try with a in instead of a regexp..
Could be this is more performant
SELECT c.user, COUNT(DISTINCT c.user)
FROM mytable AS c
JOIN (SELECT id_beneficiario, mes
FROM mytable
WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03','
L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08','
N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03') AS d
ON c.user = d.user AND c.mes = d.mes
WHERE c.codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03','
L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08','
N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03')
GROUP BY c.user;
but if you explain your related table schema and what you want obtain could is possible write a more simple query

SQL Sub-select statements filter using where clause

I am in the process of building a dashboard and need to extract some data from a somewhat complex schema.
I have a select statement (see below) that I am using to extract information, but need to conduct some filtering on part of the select statement, and I'm struggling.
select distinct j.id 'Job_Id'
, js.outcome 'Outcome'
,(select string from property where parent_sheet_id = ps.id and name= 'Build_Type') as 'Build_Type'
from job j, job_step js, property_sheet ps, property p
where j.id = js.job_id
and ps.entity_id=js.id
and ps.id=p.parent_sheet_id
and ps.entity_type='step'
and p.name = 'Id'
group by j.id
order by j.id desc;
I am sure that there is a better way of doing this query, and I would appreciate any other suggestions, but I am mostly attempting to place a filter on the nested select statement which has an alias of "Build_Type", but when I try it appears not to work. I've read some blogs that this is not possible, so I am a little stuck.
Any help would be much appreciated.
Thanks.
select
ps.id,
Build_Type.string
from
property_sheet as ps
left join
property as Build_Type
on ps.id = Build_Type.parent_sheet_id and Build_Type.name = 'Build_Type'
where Build_Type....

Symfony2, JOINS with doctrine2 or sql

I have a question about symfony2.
I have a project and I am using databases with it. I use for the most part Doctrine2 and entity classes. I like the entity class object database stuff, very handy etc.
My question is, is there a way to perform normal SQL in symfony? I always get an exception when I try to use standard SQL. I am having trouble with joins in doctrine2, so i would rather use normal SQL for that.
My join would look like this in SQL:
SELECT DISTINCT Document . *
FROM Document
INNER JOIN DocumentGruppe ON Document.id = DocumentGruppe.dokId
INNER JOIN UserGruppe ON DocumentGruppe.gruppenId = UserGruppe.gruppenId
WHERE UserGruppe.userId =9
The where clause at the end is just for testing. If I use doctrine with it's DQL it always says that there is an exception: The Variable DocumentGruppe was not defined before.
Here is my DQL query:
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN DocumentGruppe dg ON d.id = dg.dokId
INNER JOIN UserGruppe ug ON dg.gruppenId = ug.gruppenId
WHERE ug.userId =9
'
);
Does anyone know a workaround or a way to use this doctrine2 stuff to work with joins?
Every JOINED tables must be declared as associations in mapping... How is your entity defined ? Show us your mapping file (Document.php if annotation, or Resources/config/doctrine/document;xml or yml if XMl or YAML).
Your request will be something like that :
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN d.documentGruppen dg
INNER JOIN d.userGruppen ug
WHERE ug.userId =9
'
);

mySQL - WHERE, AND/OR selecting

I'm trying to select all posts from database, (where an ID is = an id from another table, which connects the people i'm in network with) OR (to select posts where i'm the writer of the post.). Actually i'm trying to get posts from people in my network AND my own.
I've found out how to do this, but when using the OR clause it's selecting the rows twice. So for example, if I write a post it's duplicated when echo'ed out from database.
My mySQL:
$sId = validate::intValidate($_SESSION['userId']);
$sql = "SELECT * FROM networkPost
INNER JOIN authentication
ON networkPost.FK_networkYou=authentication.userId
INNER JOIN network
ON networkPost.FK_networkYou=network.networkYou
WHERE networkMe=$sId AND FK_networkYou=networkYou OR networkYou=$sId
ORDER BY networkPostId DESC";
networkYou is: The userId of the post writer.
So how do I select my own posts and my networks posts?
You have few errors in your code
validate::intValidate($_SESSION['userId']); //missing square bracket
And the WHERE part of the query is missing brackets
WHERE (networkMe=$sId AND FK_networkYou=networkYou) OR networkYou=$sId
looks like you are missing '()'
$sId = validate::intValidate($_SESSION['userId');
$sql = "SELECT * FROM networkPost
INNER JOIN authentication
ON networkPost.FK_networkYou=authentication.userId
INNER JOIN network
ON networkPost.FK_networkYou=network.networkYou
WHERE (networkMe=$sId AND FK_networkYou=networkYou) OR networkYou=$sId
ORDER BY networkPostId DESC";
I found a solution on my problem. I wanna say thanks to Starx, which I might have pissed off, sorry! I'll make your answer the right one.
But here is my solution:
SELECT DISTINCT networkPost.*, authentication.* FROM networkPost
INNER JOIN authentication
ON networkPost.FK_networkYou=authentication.userId #Så jeg kan skrive hvem posteren er.
LEFT JOIN network
ON networkPost.FK_networkYou=network.networkYou
WHERE networkMe=$sId OR FK_networkYou=$sId
ORDER BY networkPostId DESC
Try this :
$sId = validate::intValidate($_SESSION['userId']);
$sql = "SELECT DISTINCT * FROM networkPost np,authentication at,network n
WHERE
np.FK_networkYou=n.networkYou AND
np.FK_networkYou=at.userId AND
np.FK_networkYou in(SELECT DISTINCT np.FK_networkYou FROM networkPost np,authentication at,network n
WHERE np.FK_networkYou=n.networkYou AND
np.FK_networkYou=at.userId AND
(networkMe=$sId AND FK_networkYou=networkYou) OR networkYou=$sId
ORDER BY networkPostId DESC");

LINQ To SQL "Group By"

I wonder if someone can help me. I want to replicate the following SQL query using LINQ in VB.Net.I'm a little unclear on how to do subqueries / aggregates.
Thanks
SELECT *
FROM Server S
INNER JOIN ServerHDD H
ON S.Server_ID = H.Server_ID
INNER JOIN (SELECT MAX(ServerHDD_ID) AS ServerHDD_ID
FROM ServerHDD
GROUP BY Server_ID, Letter) Filter
ON H.ServerHDD_ID = Filter.ServerHDD_ID
ORDER BY S.Hostname, H.Letter
Got this as below in C# => need VB.Net Conversion please.
from S in SERVER
join H in SERVERHDD on S.Server_ID equals H.Server_ID
join FILTER in
(from s in SERVERHDD group s
by new {s.Server_ID, s.Letter}
into groupedServerHDD select new
{
SERVERHDD_ID = groupedServer.Sum(gS=>gS.ServerHDD_ID)
}
)
on H.ServerHDD_ID equals FILTER.SERVERHDD_ID
orderby S.Hostname, H.Letter
select S
This is my most favorite page regarding this topic. I love LINQ to SQL (and wish they intended to continue support for it over Entity Framework...) http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx. On this page you will find all the answers to your querying needs. It is hard to format the query here without something to test it against!
Your inner joins go away with the simple join syntax of LtS. You can either say .Max() on your inner select or Max(pseudo functoid here) like this:
From p2 In g _
Where p2.UnitPrice = g.Max(Function(p3) p3.UnitPrice) _
Select p2
There are a couple of LINQ learning tools out there that are pretty cool.
This one is my favourite... LinqPad. But you might also want to check out Linqer.
You should be able to paste your code into one of them apps and it will show you how its converted. Hope they come in handy :)