Read last record from database without any unique id - mysql

I want to read last record from database but i don't have any unique id column. I am using Mysql workbench 6.3c
i tried this query :
SELECT * FROM energymetersdata where VarName='01_lab1_lsi2_kwh'
ORDER BY VarValue desc LIMIT 1;
but i got the first row

Limit ->is used to get the number of record you want to view from table,
'Order by desc'-> orders the column in descending order
first convert your date column date type to str_to_date
SELECT *,str_to_date(timestring,'%d-%m-%Y %T')as date1 FROM energymetersdata where
VarName='01_lab1_lsi2_kwh' ORDER BY date1 desc LIMIT 1;

Try this:
SELECT * FROM energymetersdata where VarName='01_lab1_lsi2_kwh'
ORDER BY TimeString desc LIMIT 1;

Try short query
SELECT * from energymetersdata HAVING MAX(TimeString);
it will return latest record which you want

You appear to have a time column called time_ms. You should use this for getting the most recent value:
SELECT emd.*
FROM energymetersdata emd
WHERE emd.VarName = '01_lab1_lsi2_kwh'
ORDER BY time_ms desc
LIMIT 1;
In particular, this can take advantage of an index on energymetersdata(VarName, time_ms), which should make the query very fast.

Related

Obtaining the maximum value with Order By and Limit 1

First of all, I am using MySQL. When I make the following query:
SELECT CodE,sum(tiempo) AS 'tiempo total'
FROM Participa
GROUP BY CodE
ORDER BY 'tiempo total' DESC LIMIT 1;
it shows me the first line of my table instead of the MAX value. However, If I make the following query:
SELECT CodE,sum(tiempo)
FROM Participa
GROUP BY CodE
ORDER BY 2 DESC LIMIT 1
I get the correct result.
I have just changed the alias 'tiempo total' for somthing that should be equivalent.
How it´s possible?
Only use single quotes for string and date constants -- never for column aliases. So:
SELECT CodE, sum(tiempo) AS `tiempo total`
FROM Participa
GROUP BY CodE
ORDER BY `tiempo total` DESC
LIMIT 1;
You are ordering by a constant string, not the name of a column. Hence, if you get the maximum in your query, it would be a total accident.
Note: You can get around these issues by giving columns names that never need to be escaped:
SELECT CodE, sum(tiempo) AS tiempo_total
FROM Participa
GROUP BY CodE
ORDER BY tiempo_total DESC
LIMIT 1;
Easier to type, too.

Excluding first and last result from sql query

I'm fairly new to SQL so this may be fairly simple but I'm trying to write a script in SQL that will allow me to get a set of data but I don't want the first or last result in the query. I can find lots on how to remove the first result and how to remove the last result but not both.
This is my query so far:
SELECT * FROM itinerary Where ID = 'A1234' ORDER BY DateTime ASC
I want to remove the first and the last record of that select based on the DateTime.
This may not be the most performant way to do this, but you didn't give any schema info, and it looks like your ID column is not unique. It would be easier if you had a primary key to work with.
SELECT * FROM itinerary
WHERE ID = 'A1234'
AND DateTime <
(SELECT MAX(DateTime) FROM itinerary WHERE ID = 'A1234')
AND DateTime >
(SELECT MIN(DateTime) FROM itinerary WHERE ID = 'A1234')
ORDER BY DateTime ASC
This will basically select every record where the ID is A1234 and the DateTime doesn't equal the max or min datetime. Please note, if you have multiple records with the same value for DateTime and that also happens to be the min or max value, you might exclude more than just the first or last.
This might be good enough though. If not, you might need to write a stored procedure and not just straight ANSI SQL.
Try this ..
select * from
(select a.*,row_number() over (partition by DateTime order by DateTime desc) as rnm
from itinerary Where ID = 'A1234')x
where rm <> 1 and rm not in (
select max(rm) from
(
select row_number() over (partition by DateTime order by DateTime desc) as rnm
from itinerary Where ID = 'A1234'))
Select in reverse order & skip first and then select in the required order from the result, skipping first.
SELECT * FROM (SELECT *
FROM itinerary
Where ID = 'A1234'
ORDER BY DateTime DESC
LIMIT 1, 18446744073709551615) x ORDER BY DateTime ASC
LIMIT 1, 18446744073709551615
18446744073709551615 is max integer just in case you wanted to know why I picked that value

select all the rows from my table except the first 20 rows

I want to select all the rows from my table except the first 20 rows. How it possible? The total number of rows are not static.
SELECT statistics_id,title, user_name FROM (
SELECT statistics_id,title, user_name FROM statistics ORDER BY statistics_id DESC
LIMIT(select count(*)from statistics )-20
) sub
ORDER BY access_statistics_id ASC
I know 'LIMIT(select count(*)from statistics )-20' is not a correct method. Please help.
the documentation says (https://dev.mysql.com/doc/refman/5.5/en/select.html) the following:
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
so you could use something like
LIMIT 20, veryLargeNumber
Try this
DECLARE v_max bigint unsigned default ~0;
SELECT statistics_id,title, user_name
FROM statistics
LIMIT 20, v_max;
After writing the select query u just have to include,
LIMIT 21,100;
21-Offset i.e from which row you want to start selecting and
100- is the Limit[Which you can set according to your need]
You actually need:
SELECT
statistics_id, title, user_name
FROM statistics
ORDER BY
statistics_id ASC
LIMIT 20, 18446744073709551615;
As per MySQL Documentation
To retrieve all rows from a certain offset up to the end of the result
set, you can use some large number for the second parameter. This
statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
If your table grows fast, selecting all rows (with exception of first 20) is not a good idea. In such case, you should batch your query, and handle a subset of entries at a time, some thing like:
SELECT * FROM tbl LIMIT 20,120;
Try using the offset option for the LIMIT syntax. you can read more about the LIMIT syntax at http://dev.mysql.com/doc/refman/5.0/en/select.html.
SELECT `statistics_id`
, `title`
, `user_name`
FROM `statistics`
ORDER BY `statistics_id` ASC
LIMIT 20, 18446744073709551615

MySQL sort by not sorting?

I am fetching rows from my DB using this request:
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY 'amount' DESC
So, obviously, i expected the returned values to be sorted in descending order by the amount column in my DB, but it doesn't? it still fetches them, but just doesn't sort them?
Any ideas here? is my SQL statement wrong?
remove single quote around amount like this and try:
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
Use below query
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
ORDER BY clause uses column name.
Column name should not give in quotes.
there fore the query becomes as follows
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC

SQL First() Function

I am using phpMyAdmin to write some SQL code that I thought was simple but proving to be a headache. I'm using this tutorial to help me out. My goal is to get the first and last columns id's from a result set. When I do this query I get 5 rows starting at 15 and going through 11.
SELECT id
FROM boardPost
WHERE recipientId = 1
ORDER BY id DESC
LIMIT 0,5
However, when I try this query I get an error #1064: "You have an error in your SQL syntax."
SELECT FIRST(id)
FROM boardPost
WHERE recipientId = 1
ORDER BY id DESC
LIMIT 0,5
Something like this maybe?
SELECT min(id), max(id)
from (
select id
from boardPost
where recipientId = 1
order by id desc
limit 0,5
) t
I think that is what you want?
Select id from boardPost order by id asc limit 1
and
Select id from boardPost order by id desc limit 1
If you just want the first and the last id of a result set, you could consider this:
SELECT MIN(id) firstId, MAX(id) lastId FROM someTable WHERE aField = 1;
Note that it'll only work if you do use and ORDER BY an AUTO_INCREMENT field, else you might get unexpected results.
It'll only work with the full set. If you need the first and last id of a limited one, you're probably better of using 2 queries with ASC and DESC order and LIMIT 1.
MySQL does not support the FIRST() function. You will need to use the workaround they specified in that tutorial (using ORDER BY and LIMIT)
In some situations (like mine, that first brought me here), there are some rarely-used MySQL "windowing functions" such as FIRST_VALUE and LAST_VALUE that may provide the functionality you're seeking.
(Here's more info on Window Function Concepts and Syntax, and the Wikipedia description of the term.)