Two separate joins on the same query - mysql

I have a query to find duplicates in a table:
SELECT sofferenze.id_soff, sofferenze.Descrizione
FROM sofferenze
INNER JOIN (
SELECT Descrizione
FROM sofferenze
GROUP BY Descrizione
HAVING count( id ) >1
)dup ON sofferenze.Descrizione = dup.Descrizione
ORDER BY Descrizione ASC
It works like a charm and gives me all the duplicated rows.
I also have another query that starting from sofferenze.id_soff will give me another value in another table:
SELECT cod_fisc
FROM anagrafiche
JOIN `rischiatura` ON anagrafiche.id_ndg = rischiatura.id_ndg
WHERE id_ogg = 'SF000000012'
AND id_ruolo = 'RU010000002'
Actually this second query is run for each row returned by the first query replacing in this line WHERE id_ogg='SF000000012' the value 'SF000000012' with the value sofferenze.id_soff that is returned by the first query.
This code is not efficient because it runs several times the second query.
Are there any option that I can merge the two queries?

Why not combine it into a sub-query?
SELECT cod_fisc
FROM anagrafiche
JOIN `rischiatura` ON anagrafiche.id_ndg = rischiatura.id_ndg
WHERE id_ogg IN (SELECT x.id_soff
FROM sofferenze x
WHERE x.Descrizione IN (
SELECT ix.Descrizione
FROM sofferenze ix
GROUP BY ix.Descrizione
HAVING count( * ) >1
))
AND id_ruolo = 'RU010000002'

Related

How do I improve the performance of my sub query?

I have the following two separate queries:
SELECT qry_tbl_G_ov_uni_atp.ID, Max(qry_tbl_G_ov_uni_atp.nElo_Ov) AS MaxOfnElo_Ov
FROM qry_tbl_G_ov_uni_atp
GROUP BY qry_tbl_G_ov_uni_atp.ID;
And:
SELECT qry_tbl_G_ov_uni_atp.ID, Max(qry_tbl_G_ov_uni_atp.nElo_Sur) AS MaxOfnElo_Sur1
FROM qry_tbl_G_ov_uni_atp
WHERE qry_tbl_G_ov_uni_atp.ID_C = 1
GROUP BY qry_tbl_G_ov_uni_atp.ID;
Both run fine and within a second or two. I want to combine them into one query so I have ID, MaxOfnElo_Ov and MaxOfnElo_Sur1 in the same output.
I know I need to use a sub query but my attempts take absolutely ages to display anything and then are barely useable as any attempt at scrolling locks Access up for an age again. I'm clearly not doing something right. Here's my sub query code:
SELECT qry_tbl_G_ov_uni_atp.ID, Max(qry_tbl_G_ov_uni_atp.nElo_Ov) AS MaxOfnElo_Ov, (SELECT Max(tt.nElo_Sur)
FROM qry_tbl_G_ov_uni_atp as tt
WHERE tt.ID_C = 1
AND tt.ID = qry_tbl_G_ov_uni_atp.ID) AS MaxOfnElo_Sur1
FROM qry_tbl_G_ov_uni_atp
GROUP BY qry_tbl_G_ov_uni_atp.ID;
You can use a subquery to achieve this as you have indicated. By using a sub-query in the JOIN as well you will get all results from a (your first query) and matching results from b (your second query):
SELECT a.ID,
a.MaxOfnElo_Ov,
b.MaxOfnElo_Sur1
FROM (
SELECT qry_tbl_G_ov_uni_atp.ID,
Max(qry_tbl_G_ov_uni_atp.nElo_Ov) AS MaxOfnElo_Ov
FROM qry_tbl_G_ov_uni_atp
GROUP BY qry_tbl_G_ov_uni_atp.ID
) a
LEFT JOIN (
SELECT qry_tbl_G_ov_uni_atp.ID,
Max(qry_tbl_G_ov_uni_atp.nElo_Sur) AS MaxOfnElo_Sur1
FROM qry_tbl_G_ov_uni_atp
WHERE qry_tbl_G_ov_uni_atp.ID_C = 1
GROUP BY qry_tbl_G_ov_uni_atp.ID
) b ON b.ID = a.ID
Note that this is untested, and assumes the ID is the same in both a and b (which I believe it is).

Getting Newest Record from a table using mysql

This has to be a no brainer, but I am stumped. I'm used to using aggregate 'FIRST' in MsAccess, but MySql has no such thing.
Here is a simple table. I want to return the most recent record based on the date,
for each unique 'group ID'. I need the three records in yellow.
I was asked to add my full query. I tried one of the suggestions using the JOIN feature replacing 't' with the temp table name, but it failed to work. "Can't reopen table 't'"
The code is below. I know it's ugly, but it does return the correct data set.
I cleaned up the code a bit and added the JOIN code. Error: "Can't reopen table 't'"
enter code here
DROP TABLE IF EXISTS `tmpMaxLookupResults`;
create temporary table tmpMaxLookupResults
as
SELECT
REPORTS.dtmReportCompleted,
RESULTS.lngMainReport_ID, RESULTS.lngLocationGroupSub_ID
FROM
(tbl_010_040_ProcedureVsTest_Sub as ProcVsSub
INNER JOIN tbl_010_050_CheckLog_RESULTS as RESULTS
ON (ProcVsSub.lngLocationGroupSub_ID = RESULTS.lngLocationGroupSub_ID)
AND (ProcVsSub.lngProcedure_ID = RESULTS.lngProcedure_ID)
AND (ProcVsSub.lngItemizedTestList_ID = RESULTS.lngItemizedTestList_ID)
AND (ProcVsSub.strPasscodeAdmin = RESULTS.strPasscodeAdmin)
AND (ProcVsSub.strCFICode = RESULTS.strCFICode))
INNER JOIN
tbl_000_010_MAIN_REPORT_INFO as REPORTS ON (RESULTS.lngPCC_ID =
REPORTS.lngPCC_ID)
AND (RESULTS.lngProcedure_ID = REPORTS.lngProcedure_ID)
AND (RESULTS.lngMainReport_ID = REPORTS.idMainReport_ID)
AND (RESULTS.strPasscodeAdmin = REPORTS.strPasscodeAdmin)
AND (RESULTS.strCFICode = REPORTS.strCFICode)
WHERE
(((RESULTS.lngProcedure_ID) = 143)
AND ((RESULTS.dtmExpireDate) IS NOT NULL)
AND ((RESULTS.strCFICode) = 'ems'))
GROUP BY RESULTS.lngMainReport_ID, RESULTS.lngLocationGroupSub_ID
ORDER BY (REPORTS.dtmReportCompleted) DESC;
SELECT t.*
FROM tmpMaxLookupResults AS t
JOIN (
SELECT lngLocationGroupSub_ID,
MAX(dtmReportCompleted) AS max_date_completed
FROM tmpMaxLookupResults
GROUP BY lngLocationGroupSub_ID ) AS dt
ON dt.lngLocationGroupSub_ID = t.lngLocationGroupSub_ID AND
dt.max_date_completed = t.dtmReportCompleted
enter code here
Try this
SELECT
tn.*
FROM
tableName tn
RIGHT OUTER JOIN
(
SELECT
groupId, MAX(date_completed) as max_date_completed
FROM
tableName
GROUP BY
groupId
) AS gt
ON
(gt.max_date_completed = nt.date_completed AND gt.groupId = nt.groupId)
You can use the following SQL.
select * from table1 order by date_completed desc Limit 1;
Use Order By
SELECT *
FROM table_name
ORDER BY your_date_column_name
DESC
LIMIT 1
In a Derived Table, get the maximum date_completed value for every group_id.
Join this result-set back to the main table, in order to get the complete row corresponding to maximum date_completed value for every group_id
Try the following query:
SELECT t.*
FROM your_table_name AS t
JOIN (
SELECT group_id,
MAX(date_completed) AS max_date_completed
FROM your_table_name
GROUP BY group_id
) AS dt
ON dt.group_id = t.group_id AND
dt.max_date_completed = t.date_completed

Counting one field in sql with join

I have a table, named rendeles_termekek.(In english, ordered_products)
I would like to count, that each product how many times was ordered.
With the SQL below, I get 4 as ennyi. I upload a picture, and I wrote the correct number to each rows.
SELECT DISTINCT
rendeles_termekek.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek ) AS ennyi
FROM rendeles_termekek
LEFT JOIN termek ON rendeles_termekek.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC
**r1** is the alias of your table rendeles_termekek so you have to access those columns through alias name "r1" like I did in below query. try below
SELECT DISTINCT
r1.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(r.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi
FROM rendeles_termekek r1
LEFT JOIN termek ON r1.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC
I think you have only four rows in your table "rendeles_termekek".
I have updated your query. try this
SELECT DISTINCT
rendeles_termekek.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi
FROM rendeles_termekek r1
LEFT JOIN termek ON rendeles_termekek.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC
Note that I have changed the sub-query and added a where condition in it
`( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi`

Performing queries on based on the output of a subquery

I am trying to perform a query based on the output of a sub-query. I would join the tables and perform one big query but that forces the query to search the entire table of one of the tables. The goal is to have the who (from table1), the what (from table2) and the when (from table3).
Here's what I have,
SELECT
DB1.TB1.`Date`,
DB1.TB1.`Sequence`,
DB1.TB1.`InstanceId`
FROM
(
SELECT
DB1.TB2.`UserName` AS USER,
DB1.TB2.`FirstName`,
DB1.TB2.`LastName`,
DB1.TB3.`ObjectName` AS OBJECT,
DB1.TB3.`ObjectType`
FROM
DB1.TB2
INNER JOIN DB1.TB3 ON DB1.TB2.`UserName` = DB1.TB3.`UserName`
INNER JOIN DB1.TB4 ON DB1.TB3.`ObjectName` = DB1.TB4.`ObjectName`
WHERE
DB1.TB4.`ADD` = 'Y' AND
DB1.TB2.`ADUC` NOT LIKE 'ServiceAccount' AND
DB1.TB3.`ObjectName` NOT IN ('ThisAdmin','ThatAdmin')
) AS MySubQuery
WHERE
DB1.TB1.`UserName` LIKE 'USER' AND
DB1.TB1.`ActionDetail` LIKE '%OBJECT%'
ORDER BY
DB1.TB1.`Date` DESC LIMIT 1

Query for self join in MySQL

I have a query which gets the correct result but it is taking 5.5 sec to get the output.. Is there any other way to write a query for this -
SELECT metricName, metricValue
FROM Table sm
WHERE createdtime = (
SELECT MAX(createdtime)
FROM Table b
WHERE sm.metricName = b.metricName
AND b.sinkName='xx'
)
AND sm.sinkName='xx'
In your code, the subselect has to be run for every result row of the outer query, which should be quite expensive. Instead, you could select your filter data in a separate query and join both accordingly:
SELECT `metricName`, `metricValue` FROM Table sm
INNER JOIN (SELECT max(`createdtime`) AS `maxTime, `metricName` from Table b WHERE b.sinkName='xx' GROUP BY `metricName` ) filter
ON (sm.`createdtime` = filter.`maxTime`) AND ( sm.`metricName` = filter.`metricName`)
WHERE sm.sinkName='xx'