SQL join left get MAX(date) - mysql

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

Related

Select the first record of another table inside a select - MYSQL

I´m trying to make a query listing all clients, and also get the last comment and
the date of that comment inside the table of history_client inside a single query for it to be listed.
select a.id_client,a.name,a.lastname,(select b.date_created,b.comentary
from history_of_client b where a.id_client = b.id_client_asociate) from clients_main_table
You could use an inner join on max(date_created) for id_client on history table and join
SELECT a.id_client,a.name,a.lastname, h.commentary
FROM clients_main_table a
INNER join (
select b.id_client_asociate, max(b.date_created) max_date
from history_of_client
group by b.id_client_asociate ) t on t.id_client_asociate = a.id_client
INNER JOIN history_of_client h on h.id_client_asociate = t.id_client_asociate
and h.date_created = t.max_date
Use the LEFT JOIN and INNER join to get your desired result set.
select a.id_client,
a.name,
a.lastname,
hc.date_created,
hc.comentary
from clients_main_table c
left join (select id_client_asociate,max(date_created) dt from history_of_client group by id_client_asociate) h
on (c.id_client = b.id_client_asociate)
inner join history_of_client hc
on (hc.id_client_asociate = b.id_client_asociate and hc.date_created = h.date_created)

Inner join or other equal solution

I have good working sql query but I need to select also atribute from table advert. I tried with inner join but it wasn't successful. So this query is ok but I need to select one atribute from table advert.
SELECT D.* FROM details
WHERE (D.name LIKE ?) AND (D.id_advert IN(
SELECT A.id
FROM advert A
WHERE A.status=1 and duration >= CURDATE()
ORDER BY duration DESC ))
You can change the in (subquery ) in a proper inner join and the is simple use the columns form table A
SELECT D.* , A.*
FROM details
INNER JOIN advert A ON D.id_advert = A.id
AND A.status=1
AND duration >= CURDATE()
WHERE D.name LIKE ?
SELECT *
FROM details D
INNER JOIN advert A ON D.id_advert = A.id
INNER JOIN place P ON A.id_place = P.id
WHERE (D.NAME LIKE ?)
AND ( D.id_advert IN (
SELECT A.id
FROM advert A
WHERE A.STATUS = 1 AND duration >= CURDATE()
ORDER BY duration DESC
)
)
Here "?" is for search key. This query work perfect.

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 order by date before selecting

I'm trying to get all topics along with the last comment in each topic. I've tried a couple of different sql statements, which haven't been working out.
SELECT
a.*,
b.*,
c.*,
(SELECT COUNT(*) FROM comments WHERE comment_topic_id = a.topic_id) AS count
FROM topics AS a
LEFT JOIN categories AS b ON a.topic_category = b.category_id
LEFT JOIN (
SELECT *
FROM comments
ORDER BY comment_date DESC
) AS c ON a.topic_id = c.comment_topic_id
WHERE b.category_id = '1' AND b.category_permission <= '2'
ORDER BY a.topic_created ASC
The above code will generate a result for each comment instead of the most recent.
Any help is appreciated, I can provide images to illustrate the database and table structures
I've changed the alias of your count because count is a reserved word.
Try this:
EDIT
SELECT
a.*,
b.*,
co.*,
(SELECT COUNT(*) FROM comments WHERE comment_topic_id = a.topic_id) AS tot_comment
FROM topics AS a
JOIN categories AS b ON a.topic_category = b.category_id
LEFT JOIN (
SELECT *
FROM comments c
WHERE NOT EXISTS(
SELECT 'NEXT'
FROM comments c2
WHERE c2.comment_topic_id = c.comment_topic_id
AND c2.comment_date > c.comment_date
)
) AS co ON a.topic_id = co.comment_topic_id
WHERE b.category_id = '1' AND b.category_permission <= '2'
ORDER BY a.topic_created ASC

Modifying MYSQL query to get a JOIN between two tables

I'm breaking my head trying to modify this query(thx sgeddes) in order to
get at result not only from db_events.events fields, instead join it with some db_system.devices fields
SELECT e.*
FROM db_events.events e
JOIN (
SELECT Max(id) MaxId, device_id
FROM db_events.events
GROUP BY device_id ) e2 on e.Id = e2.MaxId AND e.device_id = e2.device_id
WHERE e.device_id IN (
SELECT device_id
FROM db_system.devices
WHERE vendor = 1)
ORDER BY e.id DESC
How can I get it without repeat the subquery:
SELECT *
FROM db_system.devices
WHERE vendor = 1
I need get db_system.devices.brand and db_system.devices.model joined with final results, and
I tried to modify it step to step, I tried with temporary tables, I suspect it should be something simple, but I have not been able to do it, of course thank you very much...
is this what you want?
SELECT e.*, a.*
FROM db_events.events e
INNER JOIN
(
SELECT Max(id) MaxId, device_id
FROM db_events.events
GROUP BY device_id
) e2 on e.Id = e2.MaxId AND
e.device_id = e2.device_id
INNER JOIN db_system.devices a
ON e.device_id = a.device_id AND
a.vendor = 1
ORDER BY e.id DESC
the condition a.vendor = 1 can also be moved on WHERE clause and the result is still the same since you are using INNER JOIN
SELECT ....
FROM .... JOIN ....
WHERE a.vendor = 1
ORDER BY ...