Delete rows with smallest int SQL mySQL - mysql

I'm new in sql and I have some problems with complex selection. How can I delete two rows with smallest base_amount with base_currency 'USD'?

In MySQL, you can use ORDER BY and LIMIT in a DELETE:
delete from t
where base_currency = 'USD'
order by base_amount asc
limit 2;

Related

Query sql slow with order by and group by

I'm doing a database query but it's taking a while, I believe it's for the group by and the order by, but I couldn't get better.
SET #CODIGO_EMPRESA = 1;
SET #CODIGO_FILIAL = 2;
SET #DATA_INICIAL = '2021-06-16 21:59:17';
SET #DATA_FINAL = '2021-09-20 21:59:16';
SET #SITUACAO_SUP_SANG = 0;
SELECT *
FROM
(
SELECT
CODIGO_BOMBA, CODIGO_BICO, ENCERRANTE_FINAL
FROM
MOVIMENTO_COMB_ABASTECIDAS
WHERE
CODIGO_EMPRESA = #CODIGO_EMPRESA
AND CODIGO_FILIAL = #CODIGO_FILIAL
AND DATAHORA < #DATA_INICIAL
ORDER BY DATAHORA DESC , ENCERRANTE_INICIAL DESC
) A GROUP BY CODIGO_BOMBA, CODIGO_BICO
You need a multicolumn index to help this query run fast. It should contain the two columns you mention in WHERE ... = ... and then the column you mention in WHERE ... < ....
Try this:
CREATE INDEX MCA_CE_CF_D
ON MOVIMENTO_COMB_ABASTECIDAS
(CODIGO_EMPRESA, CODIGO_FILIAL, DATAHORA);
You didn't ask about this, but your query has some other problems. You're misusing MySQL's notorious nonstandard extension to GROUP BY. So its SELECT clause is interpreted as if ANY_VALUE() appeared on the third column.
SELECT CODIGO_BOMBA, CODIGO_BICO, ANY_VALUE(ENCERRANTE_FINAL)
And, because SQL is a set-processing language, it is free to ignore ORDER BY clauses in subqueries unless they're accompanied by LIMIT clauses. If it somehow is not ignoring your ORDER BY clause, that is nothing but luck.

MySQL Trigger - Update last row from table with average taken from another table

I'm having problems with creating MySQL trigger - I want to update column temp of last row of table avg_temp with an average from the last 144 records from
the temperature_C column in stats table. I am doing this through phpmyadmin before INSERT happens.
My code, hope it helps to explain what I want the code to do:
UPDATE avg_temp(`temp`)
SET (
SELECT `id`, AVG(`temperature_C`)
FROM `stats`
GROUP by `id`
LIMIT 144
)
ORDER BY id DESC
LIMIT 1
this however throws a syntax error.
If anyone could help me then that would be wonderful.
Yyou could use some subselect
and for the right avg result you should use a subselect for get 144 rows
update avg_temp
set temp = ( select avg(t1.temperature_C)
from (
SELECT id, temperature_C
FROM stats
ORDER BY id
LIMIT 144
) t1
)
where id = your_id
This should be the right syntax for MySQL update to calculate the average of last 144 values, using a sublquery:
UPDATE avg_temp SET `temp` = AVG(
(
SELECT `temperature_C`
ORDER BY id DESC
LIMIT 144
)
)
ORDER BY id DESC
LIMIT 1
You appear to want:
UPDATE avg_temp
SET `temp` = (SELECT AVG(temperature_C)
FROM (SELECT s.temperature_C
FROM stats s
ORDER BY id DESC
LIMIT 144
) s
)
ORDER BY id DESC
LIMIT 1;
However, I would be very suspicious about your desire to do this, especially in a trigger. Normally, the effect that a trigger has depends on the data in the records passed to the trigger. I cannot think of a situation where I have ever written a trigger (other than for testing or informational purposes) that does not reference such data.
You appear to be using the insert as a timing mechanism. Instead, you might just want to create a view that returns the average from the last 144 rows (or from the last 144 rows but one).

A heavy loading query not sure what's happened

I have a SQL query like this, and it takes high amount of loading...
Not sure what is happening here...if anyone could help me with this.
SELECT `posts`.* FROM `posts`
WHERE `posts`.`type`
IN ('MySubDomainSitePost')
AND `posts`.`aasm_state` = 'published'
AND (published_at <= '2015-05-12 01:01:01')
AND `posts`.`on_frontpage` = 1
AND `posts`.`is_pinned` = 0
ORDER BY published_at DESC LIMIT 16
You need to check the query performance using explain select. Now for large data-set the query will perform very poorly if the columns are not indexed.
From the given query you may need to add the following indexes
alter table posts
add index p_search_idx(type,aasm_state,published_at,on_frontpage,is_pinned);
This will boost up the speed of the query.
Make sure to take a backup of the table before applying the index.
And no need to use IN in the query it could be as
SELECT `posts`.* FROM `posts`
WHERE `posts`.`type` = 'MySubDomainSitePost'
AND `posts`.`aasm_state` = 'published'
AND (published_at <= '2015-05-12 01:01:01')
AND `posts`.`on_frontpage` = 1
AND `posts`.`is_pinned` = 0
ORDER BY published_at DESC LIMIT 16

how to retrieve two records in a table for each record in mysql

I have a "reply" table with structure.
replyno topicno replydesc replyrank
Now i need to retrieve top 2 records ordered by replyrank in descending order (means first 2 high ranked records) for each topicno (which is a foreign key).
I need a query in mysql that can extract result set like this for all topic numbers.
please give me optimized query that can execute faster
Try this:
SELECT replyno, topicno, replydesc, replyrank
FROM (SELECT replyno, topicno, replydesc, replyrank,
IF(#topicno = #topicno:=topicno, #id:=#id+1, #id:=1) AS id
FROM reply, (SELECT #id:=1, #topicno:=0) A
ORDER BY topicno, replyrank DESC
) AS A
WHERE id <= 2;
Try this Query i think it gonna work for you
SELECT replyno, topicno FROM reply ORDER BY replyrank DESC LIMIT 2

Data's order is not correct in Mysql

Here is my DB data's sample:
both two columns are int
tuanId ,tuanSort
'375579', '55'
'370576', '54'
'366222', '54'
...
'346268', '52'
'369608', '52'
'370587', '52'
'370775', '52'
...
'370225', '52'
'370588', '52'
'360758', '52'
'366390', '51'
and I try these sqls bellow:
SELECT * FROM `tuan`.`TuanItem` WHERE ... ORDER BY `tuanSort` DESC LIMIT 140,20;
SELECT * FROM `tuan`.`TuanItem` WHERE ... ORDER BY `tuanSort` DESC LIMIT 160,20;
and I get these wrong data, I want to make a pagination, but the second page has some same data in the first page:
For Example, the first pic's 17th row has shown twice in the 2 pics
So, is the sort value the same can cause such a problem? Or MySQL has problem with such a select?
Given that tuanSort is not unique, the behavior is within the specification.
You are observing that one query returns a particular row as 157th row. In another query execution, it's returned as the 161st row.
To get more deterministic sequence, specify additional columns in the ORDER BY clause, e.g.
ORDER BY tuanSort DESC, tuanId DESC
If the intent behind this sequence of statements is "paging", there are more efficient approaches, such as saving a unique, sequenced identifier from the "last" row of the previous page.
If tuanSort,tuanId tuple is unique...
WHERE tuanSort <= :last_tuanSort
AND ( tuanSort < :last_tuanSort OR tuanId < :last_tuanId )
AND ...
ORDER BY tuanSort DESC, tuanId DESC
LIMIT 20
If you fetch all twenty rows, save tuanSort and tuanId from that last row. On the next "page", supply those saved values in the query predicates.
But that's an answer to a question you didn't ask.
I think you need to refresh your database table.
Try this : Go ->TuanItem->Click Operations->Alter table order by-> select your tuanid and set as an ascending order.
I think your problem is, your getting same data in 2 query.
then change the limit 160,20 to
SELECT * FROM `tuan`.`TuanItem` WHERE ... ORDER BY `tuanSort` DESC LIMIT 140,0;
SELECT * FROM `tuan`.`TuanItem` WHERE ... ORDER BY `tuanSort` DESC LIMIT 160,141;
the 0 is the offset which means the data start at 0 and the second query start at the 141 so that you cannot get same value twice