How to efficiently get a entry with highest version in mysql table - mysql

I need to get an entry from mysql with a given id but the version should be maximum.
I have a table of entries. All entries have id and version( these two are the composite keys of the table). I need to get all entries with unique id and max version.. How do I do it efficiently.
1. do I read all and pick the max for each id.
2. do i create a column with name is_latest, index on it and set it to true when new entry is put while updating older entries to false.
3. something else. :)
This should be noted that most of the calls will be read(>99%).
let the table have n entries with id 1 and versions from 1 to n
id version name ...
1 1 abcd ...
1 2 abcd ...
1 3 defg ...
I would like to get the last entry
1 3 defg ...

In mysql you could use order by and limit 1 for a single id
select *
from my_table
order by version desc
limit 1
of for several id
use inner join for max
select *
from my_table m
inner join (
select id, max(version) max_ver
from my_table
group by id
) t on t.max_ver = m.version and t.id = m.id

I think you are looking for the MAX() function.
SELECT MAX(version) from my_table where id = your_id
You can have more information here : https://sql.sh/fonctions/agregation/max (French website)
Example here : https://www.db-fiddle.com/f/tJHG1JT6RJLGJJoamYHXzQ/1

See this db-fiddle: https://www.db-fiddle.com/f/wMxb7S5tCGVA8gsXLHUHS3/0
SELECT t2.id, t2.version, t1.name
FROM my_table t1
JOIN (
SELECT id, max(version) version FROM my_table GROUP BY id
) t2 ON t1.id = t2.id AND t1.version = t2.version

Related

why the sql correct and the inner mechanism for run it?

the sql as follows come from mysql document. it is:
SELECT * FROM t1 AS t
WHERE 2 = (SELECT COUNT(*) FROM t1 WHERE t1.id = t.id);
The document say It finds all rows in table t1 containing a value that occurs twice in a given column , and doesnot explain the sql.
t1 and t is the same table, so the
count(*) in subquery == select count(*) from t
, isn't it?
count(*) in subquery == select count(*) from t
is wrong. because in mysql you can't use it like that. so you have to run it like that to get result of same id having two rows.
if you want to get count of same occurrence,
SELECT id, name, count(*) AS all_count FROM t1 GROUP BY id HAVING all_count > 1 ORDER BY all_count DESC
And also you can get values as your query like this as well,
select * from t1 where id in ( select id from t1 group by id having count(*) > 1 )
The query contains a correlated subquery in WHERE clause:
SELECT COUNT(*) FROM t1 WHERE t1.id = t.id
It is called correlated because it is related to the main query via t.id. So, this subquery counts the number of records having an id value that is equal to the current id value of the record returned by the main query.
Thus, predicate
(SELECT COUNT(*) FROM t1 WHERE t1.id = t.id) = 2
evaluates to true for any row with an id value that occurs twice in the table.
SELECT * FROM t1 AS t
WHERE 2 = (SELECT COUNT(*) FROM t1 WHERE t1.id = t.id);
This query goes through each record in t1 and then in the subquery looks into t1 again to see if in this case id is found 2 times (and only 2 times). You can do the same for any other column in t1 (or any table for that matter).
When you would like to see all values that are multiple times in the table, change WHERE 2 = by WHERE 1 <. This will also give you the values that are 3 times, 4 times, etc. in the table.
{
SELECT id,count( * )
FROM
MyTable
group by id
having count( * )>1
}
with this code, you can see the rows which repet more than one,
and you can change this query by yourself
How about using GROUP BY and HAVING:
SELECT id, count(1) as Total FROM MyTable AS t1
GROUP BY t1.id
HAVING Total = 2

mysql:how to get max id from duplicated row group by 2 columns?

I have one table name "sections_content" that has the following columns
and I want to get max id for each statecode and policyname
So ,for example,the result of statecode CN / IL /IE should be
How should I write the code for mysql ?
thanks.
I think you can solve this with a JOIN on the MAX for that group:
SELECT * FROM sections_content as t
JOIN
(
SELECT MAX(id) as id
FROM sections_content AS tbl
GROUP BY
tbl.policyName,
tbl.statecode
) AS maxId
ON maxId.id=t.id
I think you can use ORDER BY and LIMIT keywords to get the maximum number.
Exp: Having tables; table1 and table2 as in your database. check below queries.
SELECT table1.id, table2.statecode, table2.policyname, sections_content.student_lga_of_origin
FROM table1
JOIN table2
ON table1.policyname = table2.policyname
ORDER BY table1.id DESC
LIMIT 1
OFFSET 1

Count number of times, a number appears and update it to a different column

I am not sure how to do this in mysql, i have searched but I can't seem to find a solution.
,
I have a table like so.
id pid occurrence
1 23 blank
2 23 blank
3 44 blank
Basically, occurrence should have the value of 2, for id 1,2 and a value of 1 for id 3.
Any help would be appreciated. I can easily call count and GROUP BY, and get the number of times each one occurance, but I would like to update column occurrence in the right place for each pid.
To get the correct occurrence value you can do
select pid, count(*) as occurrence
from your_table
group by pid
To update the table do
update your_table t1
join
(
select pid, count(*) as occurrence
from your_table
group by pid
) t2 on t1.pid = t2.pid
set t1.occurrence = t2.occurrence
If you want to set the value in the table, use update with a join:
update table t join
(select pid, count(*) as cnt
from table
group by pid
) tt
on tt.pid = t.pid
set t.occurrence = tt.cnt;

UPDATE table using IN and COUNT

I am updating my table setting a field named "status" based on the condition that the total number of distinct rows should be more than 10 and less than 13. The query is as follows:
update myTable set status='Established'
where id IN(select id, count(*) as c
from myTable
where year>=1996 and year<=2008
group by id
having count(distinct year)>=10 and count(distinct year)<=13)
The problem is, I'm getting error1241 that is "operand should contain 1 column"! Could you please advise how can I solve this? Thanks!
The result of the sub query must return only 1 column :
update myTable set status='Established'
where id IN(select id
from myTable
group by id
having count(distinct year)>=10 and count(distinct year)>=13)
In MySQL, an update with a join often performs better than an update with a subquery in the where clause.
This version might have better performance:
update myTable join
(select id, count(*) as c
from myTable
where year >= 1996 and year <= 2008
group by id
having count(distinct year) >= 10 and count(distinct year) <= 13
) filter
on myTable.id = filter.id
set status = 'Established';
I will also note that you have a table where a column called id is not unique among the rows. Typically, such a column would be a primary key, so the having clause would always fail (there would only be one row).
update myTable
set status='Established'
where id IN(select id from myTable
group by id
having count(distinct year)>=10
and count(distinct year)>=13)
You are using IN operator and then you inner query returns two columns id and count(*) it should return only one column back.

Delete records from a table where < max number for a field and keep highest number

I know this sounds rather confusing but I'm at a loss how to explain it better. I have a table simplified below:
DB Type ID
================
Table1 1
Table1 2
Table1 3
Table1 4
Table1 5
Table2 6
Table2 7
Table2 8
Table2 9
Table2 10
what i am trying to achieve is to basically clean out this table but keep the record with the highest ID for each DB Type if that makes sense - so in this case it would be (Table1,5) and (Table2,10) with all other records being deleted. Is it possible to do this exclusively through MySQL?
*EDIT***
Answer thanks to tips from Yogendra Singh
DELETE FROM MyTable WHERE ID NOT IN (SELECT * FROM (SELECT MAX(ID) from MyTable GROUP BY DB Type) AS tb1 ) ORDER BY ID ASC
TRY selecting the max ID group by db_type first and then use it as sub query with not in.
DELETE FROM MyTable
WHERE ID NOT IN
(SELECT ID FROM
(SELECT MAX(ID) AS ID from MyTable GROUP BY DB Type) AS tb1
)
EDIT:
DELETE FROM MyTable
HAVING MAX(ID) > ID;
delete your_table
from
your_table left join
(select max(id) max_id from your_table group by type) mx
on your_table.id=mx.max_id
where mx.max_id is null
Subquery returns the maximum id for every type, and those are the values to keep. With an left join i'm selecting all the rows from your table that don't have an in in max_ids, and those are the rows to delete. This will work only if id is primary key, otherwise we have to join also the type.
Is the combination DB Type - ID unique?
If so, you can attack this in two stages:
Get only the rows you want
SELECT [DB Type], Max(ID) AS MaxID
FROM YourTable
GROUP BY [DB Type]
Delete the rest (Wrapping the previous statement into a more complicated statement; don't mean that)
DELETE FROM YourTable
FROM
YourTable
LEFT JOIN
(SELECT [DB Type], Max(ID) AS MaxID
FROM YourTable GROUP BY [DB Type]) DontDelete
ON
YourTable.[DB Type]=DontDelete.[DB Type] AND
YourTable.ID=DontDelete.MaxID
WHERE
DontDelete.[DB Type] IS NULL
DELETE FROM MyTable del
WHERE EXISTS (
(SELECT *
FROM MyTable xx
WHERE xx."db Type" = del."db Type"
AND xx.id > del.id
);
delete from my_Table
where Day in (select MAX(day) d from my_Table where id='id')