Sub Query and JOINs - mysql

I have 3 tables concerning complains. The first table consists of the complain information itself, 2nd one is the complain_review with status_id, and the 3rd is the status_id table consisting status information. I'm trying to select the complain_desc from complain and latest status_id from complain_review (sort by date desc) and couple that with complain_status information.
This is what I've tried (no success so far):
SELECT c1.complain_desc, c2.status_id, c2.name as statusDesc from complain c1
left join
(SELECT c3.status_id, c4.name, c3.complain_id FROM complain_review c3
inner join complain_status c4 on c4.id=c3.status_id ORDER by c3.date DESC) c2
on c2.complain_id=c1.id
this is the updated example provided by #maheshiv
.. I've searched through the site but I don't exactly know what keyword to search concerning this matter :(
Edit: I've build a schema at http://sqlfiddle.com/#!9/d86a7a/2 so perhaps somebody could give take a better look at the tables
Edit: Perhaps this would be the closest as I could get .. and working!
SELECT c.complain_desc, cr1.status_id, cs.name
FROM complain c
INNER JOIN complain_review cr1 ON c.id=cr1.complain_id
INNER JOIN complain_status cs ON cs.id=cr1.status_id
WHERE cr1.date = (SELECT MAX(cr2.date) FROM complain_review cr2
WHERE cr1.complain_id=cr2.complain_id)

I'm trying to select the complain_desc from complain and latest status_id from complain_review (sort by date desc) and couple that with complain_status information.
This is a very common question on Stack Overflow. You can follow the greatest-n-per-group to find many solutions.
Here's a solution using your example:
SELECT c.complain_desc, latest_cr.status_id, cs.name AS status_desc
FROM complain AS c
INNER JOIN (
SELECT complain_id, status_id
FROM (
SELECT cr.complain_id, cr.status_id,
IF(#cgroup=cr.complain_id, #rownum:=#rownum+1, 1) AS rownum,
(#cgroup:=cr.complain_id)
FROM (SELECT #cgroup:=0, #rownum:=1) AS _init
CROSS JOIN complain_review AS cr
ORDER BY cr.complain_id DESC, cr.date DESC
) AS n
WHERE n.rownum = 1
) AS latest_cr
ON c.id=latest_cr.complain_id
INNER JOIN complain_status AS cs
ON cs.id = latest_cr.status_id;
Here's a different solution using no subqueries:
SELECT c.complain_desc, cr1.status_id, cs.name AS status_desc
FROM complain AS c
INNER JOIN complain_review AS cr1
ON cr1.complain_id = c.id
LEFT OUTER JOIN complain_review AS cr2
ON cr2.complain_id = c.id AND (cr2.date > cr1.date OR cr2.date = cr1.date AND cr2.id > cr1.id)
INNER JOIN complain_status AS cs
ON cs.id = cr1.status_id
WHERE cr2.id IS NULL;

I think you may need this query,
I believe max status_id is the latest status for complaint. As per http://sqlfiddle.com/#!9/d86a7a/15
select c1.complain_desc, c2.status_id, c3.name from complain c1 inner join (select complain_id, max(status_id) from complain_review group by complain_id) c2 on c1.id=c2.complain_id inner join complain_status c3 on c3.id=c2.status_id;

Related

Improve MySql query left outer joins with subquery

We are maintaining a history of Content. We want to get the updated entry of each content, with create Time and update Time should be of the first entry of the Content. The query contains multiple selects and where clauses with so many left joins. The dataset is very huge, thereby query is taking more than 60 seconds to execute. Kindly help in improving the same. Query:
select * from (select * from (
SELECT c.*, initCMS.initcreatetime, initCMS.initupdatetime, user.name as partnerName, r.name as rightsName, r1.name as copyRightsName, a.name as agelimitName, ct.type as contenttypename, cat.name as categoryname, lang.name as languagename FROM ContentCMS c
left join ContentCategoryType ct on ct.id = c.contentType
left join User user on c.contentPartnerId = user.id
left join Category cat on cat.id = c.categoryId
left join Language lang on lang.id = c.languageCode
left join CopyRights r on c.rights = r.id
left join CopyRights r1 on c.copyrights = r1.id
left join Age a on c.ageLimit = a.id
left outer join (
SELECT contentId, createTime as initcreatetime, updateTime as initupdatetime from ContentCMS cms where cms.deleted='0'
) as initCMS on initCMS.contentId = c.contentId WHERE c.deleted='0' order by c.id DESC
) as temp group by contentId) as c where c.editedBy='0'
Any help would be highly appreciated. Thank you.
Just a partial eval and suggestion because your query seems non properly formed
This left join seems unuseful
FROM ContentCMS c
......
left join (
SELECT contentId
, createTime as initcreatetime
, updateTime as initupdatetime
from ContentCMS cms
where cms.deleted='0'
) as initCMS on initCMS.contentId = c.contentId
same table
the order by (without limit) in a subquery in join is unuseful because join ordered values or unordered value produce the same result
the group by contentId is strange beacuse there aren't aggregation function and the sue of group by without aggregation function is deprecated is sql
and in the most recente version for mysql is not allowed (by deafult) if you need distinct value or just a rows for each contentId you should use distinct or retrive the value in a not casual manner (the use of group by without aggregation function retrive casual value for not aggregated column .
for a partial eval your query should be refactored as
SELECT c.*
, c.initcreatetime
, c.initupdatetime
, user.name as partnerName
, r.name as rightsName
, r1.name as copyRightsName
, a.name as agelimitName
, ct.type as contenttypename
, cat.name as categoryname
, lang.name as languagename
FROM ContentCMS c
left join ContentCategoryType ct on ct.id = c.contentType
left join User user on c.contentPartnerId = user.id
left join Category cat on cat.id = c.categoryId
left join Language lang on lang.id = c.languageCode
left join CopyRights r on c.rights = r.id
left join CopyRights r1 on c.copyrights = r1.id
WHERE c.deleted='0'
) as temp
for the rest you should expiclitally select the column you effectively need add proper aggregation function for the others
Also the nested subquery just for improperly reduce the rows don't help performance ... you should also re-eval you data modelling and design.

Getting max record on varchar field

I have this query
SELECT
s.account_number,
a.id AS 'ASPIRION ID',
a.patient_first_name,
a.patient_last_name,
s.admission_date,
s.total_charge,
astat.name AS 'STATUS',
astat.definition,
latest_note.content AS 'LAST NOTE',
a.insurance_company
FROM
accounts a
INNER JOIN
services s ON a.id = s.account_id
INNER JOIN
facilities f ON f.id = a.facility_id
INNER JOIN
account_statuses astat ON astat.id = a.account_status_id
INNER JOIN
(SELECT
account_id, MAX(content) content, MAX(created)
FROM
notes
GROUP BY account_id) latest_note ON latest_note.account_id = a.id
WHERE
a.facility_id = 56
My problem comes from
(SELECT
account_id, MAX(content) content, MAX(created)
FROM
notes
GROUP BY account_id)
Content is a varchar field and I am needed to get the most recent record. I now understand that MAX will not work on a varchar field the way that I want it. I am not sure how to be able to get the corresponding content with the MAX id and group that by account id on in this join.
What would be the best way to do this?
My notes table looks like this...
id account_id content created
1 1 This is a test 2011-03-16 02:06:40
2 1 More test 2012-03-16 02:06:40
Here are two choices. If your content is not very long and don't have funky characters, you can use the substring_index()/group_concat() trick:
(SELECT account_id,
SUBSTRING_INDEX(GROUP_CONCAT(content ORDER BY created desc SEPARATOR '|'
), 1, '|') as content
FROM notes
GROUP BY account_id
) latest_note
ON latest_note.account_id = a.id
Given the names of the columns and tables, that is likely not to work. Then you need an additional join or a correlated subquery in the from clause. I think that might be easiest in this case:
select . . .,
(select n.content
from notes n
where n.account_id = a.id
order by created desc
limit 1
) as latest_note
from . . .
The advantage to this method is that it only gets the notes for the rows you need. And, you don't need a left join to keep all the rows. For performance, you want an index on notes(account_id, created).
SELECT
s.account_number,
a.id AS 'ASPIRION ID',
a.patient_first_name,
a.patient_last_name,
s.admission_date,
s.total_charge,
astat.name AS 'STATUS',
astat.definition,
latest_note.content AS 'LAST NOTE',
a.insurance_company
FROM
accounts a
INNER JOIN services s ON a.id = s.account_id
INNER JOIN facilities f ON f.id = a.facility_id
INNER JOIN account_statuses astat ON astat.id = a.account_status_id
INNER JOIN
(SELECT account_id, MAX(created) mxcreated
FROM notes GROUP BY account_id) latest_note ON latest_note.account_id = a.id and
latest_note.mxcreated = --datetime column from any of the other tables being used
WHERE a.facility_id = 56
You have to join on the max(created) which would give the latest content.
Or you can change the query to
SELECT account_id, content, MAX(created) mxcreated
FROM notes GROUP BY account_id
as mysql allows you even if you don't include all non-aggregated columns in group by clause. However, unless you join on the max date you wouldn't get the correct results.
The last created record is the one for which does not exist a newer one. Hence:
SELECT
s.account_number,
a.id AS "ASPIRION ID",
a.patient_first_name,
a.patient_last_name,
s.admission_date,
s.total_charge,
astat.name AS "STATUS",
astat.definition,
latest_note.content AS "LAST NOTE",
a.insurance_company
FROM accounts a
INNER JOIN services s ON a.id = s.account_id
INNER JOIN facilities f ON f.id = a.facility_id
INNER JOIN account_statuses astat ON astat.id = a.account_status_id
INNER JOIN
(
SELECT account_id, content
FROM notes
WHERE NOT EXISTS
(
SELECT *
FROM notes newer
WHERE newer.account_id = notes.account_id
AND newer.created > notes.created
)
) latest_note ON latest_note.account_id = a.id
WHERE a.facility_id = 56;

mySQL Sub Select needed

I have three tables, libraryitems, copies and loans.
A libraryitem hasMany copies, and a copy hasMany loans.
I'm trying to get the latest loan entry for a copy only; The query below returns all loans for a given copy.
SELECT
libraryitems.title,
copies.id,
copies.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM copies
INNER JOIN libraryitems ON copies.libraryitemid = libraryitems.id AND libraryitems.deletedAt IS NULL
LEFT OUTER JOIN loans ON copies.id = loans.copyid
WHERE copies.libraryitemid = 1
ORDER BY copies.id ASC, loans.createdAt DESC
I know there needs to be a sub select of some description in here, but struggling to get the correct syntax. How do I only return the latest, i.e MAX(loans.createdAt) row for each distinct copy? Just using group by copies.id returns the earliest, rather than latest entry.
Image example below:
in the subquery , getting maximum created time for a loan i.e. latest entry and joining back with loans to get other details.
SELECT
T.title,
T.id,
T.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM
(
SELECT C.id, C.qruuid, L.title, MAX(LN.createdAt) as maxCreatedTime
FROM Copies C
INNER JOIN libraryitems L ON C.libraryitemid = L.id
AND L.deletedAt IS NULL
LEFT OUTER JOIN loans LN ON C.id = LN.copyid
GROUP BY C.id, C.qruuid, L.title) T
JOIN loans ON T.id = loans.copyid
AND T.maxCreatedTime = loans.createdAt
A self left join on loans table will give you latest loan of a copy, you may join the query to the other tables to fetch the desired output.
select * from loans A
left outer join loans B
on A.copyid = B.copyid and A.createdAt < B.createdAt
where B.createdAt is null;
This is your query with one simple modification -- table aliases to make it clearer.
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
With this as a beginning let's think about what you need. You want the load with the latest createdAt date for each c.id. You can get this information with a subquery:
select l.copyid, max(createdAt)
from loans
group by l.copyId
Now, you just need to join this information back in:
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid LEFT JOIN
(SELECT l.copyid, max(l.createdAt) as maxca
FROM loans
GROUP BY l.copyid
) lmax
ON l.copyId = lmax.copyId and l.createdAt = lmax.maxca
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
This should give you the most recent record. And, the use of left join should keep all copies, even those that have never been leant.

Sum of unique rows of joined table

I have 3 tables. practices, adjustments and claims.
I need to select all practices with additional column adjustments.amount + count(claims.id)
Here is my query.
SELECT
practices.*,
(
SUM(adjustments.amount) + count(claims.id)
) as accurred_fees
INNER JOIN adjustments ON adjustments.practice_id = practices.id
INNER JOIN claims ON claims.practice_id = practices.id
GROUP BY practices.id
In my database I have 1 practice, 20 claims and 1 adjustment with amount equal to 2. SUM(eligible_fee_adjustments.amount) in query always returns 40, I guess it's 2 * count(claims.id), I don't know why it behaves like that. Could you please help me to find solution. Thanks in advance
You have a problem of joining along two different dimensions, so the rows are multiplying. You can solve this by pre-aggregating the data. The following will fix this particular problem:
SELECT p.*,
(SUM(a.amount) + c.cnt) as accurred_fees
FROM practices p INNER JOIN
adjustments a
ON a.practice_id = p.id INNER JOIN
(SELECT practice_id, count(*) as cnt
FROM claims c
GROUP BY practice_id
) c
ON c.practice_id = p.id
GROUP BY p.id;
You should probably preaggregate the adjustments as well:
SELECT p.*,
(a.amount + c.cnt) as accurred_fees
FROM practices p INNER JOIN
(SELECT practice_id, SUM(amount) as amount
FROM adjustments a
GROUP BY practice_id
) a
ON a.practice_id = p.id INNER JOIN
(SELECT practice_id, count(*) as cnt
FROM claims c
GROUP BY practice_id
) c
ON c.practice_id = p.id
GROUP BY p.id;
And you might want to consider LEFT OUTER JOIN rather than INNER JOIN so you get all practices, even those that might be missing adjustments or claims.

SQL join left get MAX(date)

i have these tables :
notice
id INT
cdate DATETIME
...
theme
id
name
notice_theme
id_notice
id_theme
I want to get the latest notices for each theme.
SELECT id_theme, n.id
FROM notice_theme
LEFT JOIN (
SELECT id, cdate
FROM notice
ORDER BY cdate DESC
) AS n ON notice_theme.id_notice = n.id
GROUP BY id_theme
The result is not good. An idea ? Thanks.
There are so many ways to solve this but I'm used to do it this way. An extra subquery is needed to separately calculate the latest cDate for every ID.
SELECT a.*, c.*
FROM theme a
INNER JOIN notice_theme b
ON a.ID = b.id_theme
INNER JOIN notice c
ON b.id_notice = c.ID
INNER JOIN
(
SELECT a.id_theme, MAX(b.DATE_CREATE) max_date
FROM notice_theme a
INNER JOIN notice b
ON a.ID_Notice = b.ID
GROUP BY a.id_theme
) d ON b.id_theme = d.id_theme AND
c.DATE_CREATE = d.max_date
SQLFiddle Demo