Consults with subqueries and use of regexp - mysql

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

Related

How to optimize a query that is a join of 2 very similar queries but with different aggregation

I have the following query:
SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM
(SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS
JOIN
(SELECT `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS
ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object
which produces the following result:
As you can see I'm basically running the same query twice. The reason for that is that I need to have that count_errors broken down by each aggregation of object + description, but I also need the count_total to be only aggregated by object. This was the way I could think of. Now I'd like to know if this is the best I can do or if it can be optimized even further.
If so I have no clue how. Googling and searching similar topics on this is difficult because the optimization task depends on the query itself, so keywords here didn't help me much.
Get rid of the inner ORDER BYs; they do nothing useful.
Rewrite the query something like this:
SELECT
me.description,
me.object,
SUM(...) AS count_errors,
SUM(...) AS count_total
FROM `metrics_event` AS me
INNER JOIN `metrics_session` AS ms ON (me.`session_id` = ms.`id`)
WHERE ms.`training_id` = 4
ms.`completed_at` IS NOT NULL
GROUP BY me.`description`, me.`object`
ORDER BY `count_total` DESC
Since a boolean expression evaluates as 1 for TRUE, else 0, devise the argument to SUM() to be a boolean expression that provides the desired COUNT.

Perform a SQL Query

I have this query in PHP MySQL PDO:
SELECT p.las_plano_id, p.mensalidade_diferenciada, v.las_tipos_planos_id, t.valor_mensalidade
FROM isw_planos AS p
INNER JOIN isw_planos_vinculos AS v
ON p.las_plano_id =
(SELECT v.las_plano_id
FROM isw_planos_vinculos
WHERE v.data_encerramento IS NULL
ORDER BY v.data_adesao
DESC LIMIT 1)
INNER JOIN isw_planos_tipos AS t
ON v.las_tipos_planos_id = t.id
WHERE p.ativo = 1
But.. the result generate a long delay.. it's possible to perform this query to execute more fast?
Thnaks..
I suspect the error is with v.:
This looks wrong: SELECT v.las_plano_id ... since v is outside the subquery. Please check the aliases used.
If removing v. does not help, please provide SHOW CREATE TABLE so we can see the indexes, etc.

Calculate between two statements

I got two statements and I want to calculate their values. Both values have to be calculated 5 - 5 = ( I want to see the answer 0 )
SELECT COUNT(*) AS 'Aantal stoelen geboekt'
FROM Boekingsregel, Vlucht
WHERE Boekingsregel.Vlucht_Vlucht_Id = Vlucht.Vlucht_Id
AND Vlucht_Datum = '2017-04-10';
SELECT min(Vliegtuig_Aantal_Stoelen) AS 'Max aantal stoelen'
FROM Vliegtuig;
While I do not see any relation of the two queries you also should not use an alias with spaces. Make your alias as short as possible but can define what value it holds, but since this is your query you know better than I do.
As for your problem you can combine the two queries into one something like this:
SELECT BR.`Aantal stoelen geboekt` - VT.`Max aantal stoelen` AS TheResult
FROM (SELECT COUNT(*) AS `Aantal stoelen geboekt`
FROM Boekingsregel, Vlucht
WHERE Boekingsregel.Vlucht_Vlucht_Id = Vlucht.Vlucht_Id
AND Vlucht_Datum = '2017-04-10') BR,
(SELECT min(Vliegtuig_Aantal_Stoelen) AS `Max aantal stoelen` FROM Vliegtuig) VT;
NOTE: Not tested I just type it here.
If this is not what you are looking for then maybe you should explain your requirements in greater detail so dhat everyone can understand and will be able to help you.
First, learn to use proper JOIN syntax.
Second, combine these in the FROM clause.
SELECT COUNT(*) AS AantalStoelenGeboekt, vt.MaxAantalStoelen
FROM Boekingsregel b JOIN
Vlucht v
ON b.Vlucht_Vlucht_Id = v.Vlucht_Id CROSS JOIN
(SELECT min(Vliegtuig_Aantal_Stoelen) AS MaxAantalStoelen
FROM Vliegtuig
) vt
WHERE v.Vlucht_Datum = '2017-04-10';
Note: MySQL allows this syntax. Perhaps a cleaner way is to use an aggregation function on MaxAantalStoelen:
SELECT COUNT(*) AS AantalStoelenGeboekt,
MAX(vt.MaxAantalStoelen) as MaxAantalStoelen
FROM Boekingsregel b JOIN
Vlucht v
ON b.Vlucht_Vlucht_Id = v.Vlucht_Id CROSS JOIN
(SELECT min(Vliegtuig_Aantal_Stoelen) AS MaxAantalStoelen
FROM Vliegtuig
) vt
WHERE v.Vlucht_Datum = '2017-04-10';

How do I convert this SQL query into hibernate

Can someone please tell me how to convert this SQL query into hibernate?
SELECT * FROM sys_quote_master AS g1
INNER JOIN
(SELECT order_base_id, order_id FROM sys_quote_master
GROUP BY order_base_id, order_date_last_revised
ORDER BY order_date_last_revised desc) AS g2
ON g2.order_id = g1.order_id;
Basically,
I have tried this and it doesn't work:
DetachedCriteria crit1 = DetachedCriteria.forClass(QuoteMaster.class);
ProjectionList pList = Projections.projectionList();
pList.add(Projections.groupProperty("orderBaseId"));
session = HibernateSessionFactory.currentSession();
Criteria crit = session.createCriteria(QuoteMaster.class);
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
c.setProjection(pList);
I get this error:
org.hibernate.QueryException: could not resolve property: this of:
QuoteMaster
And I think it has to do with this line of code were I am trying to create an inner join to the same table:
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
So basically, my question is 'How to create a join to the same table using Criteria.createCriteria or Criteria.createAlias?' The doc for Criteria class states the first parameter is a dot-separated property path, but what the heck does that mean? :)
Every example I found so far shows how to do this with 2 or 3 tables but not to the same table and I have no idea what to use for the first argument.
I dont know how your entities are, this should give rough idea.
from SystQuoteMasterEntity sqm join ( select sqm1.orderbaseid, sqm1.orderId from SystQuoteMasterEntity sqm1 group by orderbaseid,orderdatelastrev order by orderdatelast desc) g2

MySQL error code 1064 syntax error

This is a very specific question to the kind of code i have written for postgresql and i am migrating to mysql for project requirements.
The code written so far in mysql is as follows :
(select substring(dt,1,9) as dt,concat(vish,visl,visn) as vis,ip
from assignment_walmart.b
where service='ss' and ua not like '%ktxn%'
and ua not like '%khte%'
and ua not like '%keynote%'
group by 1,2,3
) as A1
left join // This is where it shows the error.
(select ip,flag from
assignment_walmart.b1
group by 1,2
) as A2
on A1.ip=A2.ip
where A2.flag is NULL
group by 1,2;
The error is popping up near the naming of the two selected tables as "A1" and "A2", so i'm assuming it's not allowed in mysql.
Can you please help me with an alternate syntax for the above code as I have to use the two tables in this manner only to join in to get required results.
How exactly do i use alias or join 2 tables in such a manner which was clearly working in postgresql?
Any help would be appreciated.
You have a subquery joined to another query. This shouldn't work in either database. You need to wrap these in a select or something like that:
select A2.dt, A2.vis, count(*)
from (select substring(dt,1,9) as dt, concat(vish,visl,visn) as vis,ip
from assignment_walmart.b
where service='ss' and ua not like '%ktxn%'
and ua not like '%khte%'
and ua not like '%keynote%'
group by substring(dt,1,9), concat(vish,visl,visn), ip
) as A1 left join // This is where it shows the error.
(select ip,flag from
assignment_walmart.b1
group by ip, flag
) as A2
on A1.ip=A2.ip
where A2.flag is NULL
group by A2.dt, A2.vis;
I am making a guess on what you want for the outer query and what the aggregation fields are. It is a good idea to be explicit about which fields are being aggregated.
It looks like you are missing the SELECT ... FROM on the outer query.
It looks you mean for your query to be of the form:
SELECT ...
FROM ( inline view query ) A1
LEFT
JOIN ( inline view query ) A2
ON A1.col = A2.col ...
WHERE ...
GROUP BY ...