how to use last() function in where clause in mysql [duplicate] - php

can i use aggregation function (LAST) in mysql??
if yes then why give me error for following query::
SELECT `user_id`,last(`value`)
FROM `My_TABLE`
group by `user_id`
ERROR:: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(value) FROM My_TABLE group by user_id' at line 1
EDIT:: I got answer "last" is not used in MySql. then How to perform it in MySql??

No, There is nothing called LAST in mysql
See the list of aggregated function
EDIT
You can perform the same something like this
select f.user_id, f.value
from (
select MAX(value) as maxval
from my_table group by user_id
) as x inner join my_table as f on f.value = x.maxval

Something like this -
SELECT * FROM table1 t1
JOIN (SELECT depno, MAX(id) max_id FROM table1 GROUP BY depno) t2
ON t1.depno = t2.depno AND t1.id = t2.max_id

There is no "last" function defined in MySQL. Are you just trying to get the last (newest) record?
If so:
SELECT `user_id`, `value`
FROM `My_TABLE`
ORDER BY `user_id` DESC
LIMIT 1;
or
SELECT `user_id`, `value`
FROM `My_TABLE`
WHERE `user_id` = (SELECT MAX(`user_id`));

Because there is no such function called as last() in mysql..
Try to use group, order by clause in mysql

The best way I found how to handle this:
SELECT user_id, json_unquote(json_extract(json_objectagg('value', value), '$.value'))
FROM my_table
GROUP BY user_id

Related

Alternative of NOT EXISTS in MySQL as query is taking time to execute with NOT EXISTS

Dummy table:
id FileName DateLastSaved
1 Marium.doc 2015-01-01
2 Amna.doc 2016-01-01
3 Marium.doc 2016-01-01
I want the query to return such rows where FileName is unique in the whole table. Rows should be returned for particular date range.
Suppose date ranges are of 2016 only, so third row should not be returned as FileName is not unique.
The query that I have created is:
$presentquery="SELECT * FROM InitialLog i WHERE MDid='$MDid' AND
(DateLastSaved>='$firstdate' AND DateLastSaved<='$presentdate') AND NOT
EXISTS (SELECT id FROM InitialLog i2 WHERE i2.id<i.id AND i.FileName=i2.FileName )";
(Where $firstdate and $presentdate are 2 dates for date ranges)
The query is returning the accurate results but it's taking time to execute. Is there any other way that I can rewrite this query??
(I have table with many rows)
I put this query together and it returns the results very quickly.
Select *
FROM foo
Where (`datelastsaved` > '2015-12-31' && `datelastsaved` < '2017-01-01')
AND `filename` NOT IN (
Select `filename`
FROM foo
GROUP BY `filename`
HAVING COUNT(*) > 1);
The first part is your normal select statement with the where clauses to filter on the dates.
The second part is the NOT IN where the select statement finds all of the ones with duplicate filenames.
Select `filename` FROM foo GROUP BY `filename` HAVING COUNT(*) > 1)
You can get the same logic using a LEFT JOIN and looking for nulls, that is,
$presentquery = "SELECT DISTINCT i.* FROM InitialLog i
LEFT JOIN InitialLog i2 ON i2.id<i.id AND i.FileName=i2.FileName
WHERE i.MDid='$MDid'
AND i.DateLastSaved>='$firstdate'
AND i.DateLastSaved<='$presentdate'
AND i2.id IS NULL";
This way you are doing a single join rather than subquerying against each value in i.
It looks like you are trying to get the data associated with the first occurrence of each file name, this should work:
SELECT *
FROM InitialLog i
WHERE MDid='$MDid'
AND DateLastSaved>='$firstdate'
AND DateLastSaved<='$presentdate'
AND id IN (SELECT MIN(id) FROM InitialLog GROUP BY FileName)
;
Alternatively, you can do a JOIN with the same subquery instead:
SELECT i.*
FROM InitialLog AS i
INNER JOIN (SELECT MIN(id) AS id
FROM InitialLog
GROUP BY FileName
) AS firsts USING (id)
WHERE i.MDid='$MDid'
AND i.DateLastSaved>='$firstdate'
AND i.DateLastSaved<='$presentdate'
;

Filtering results When date is max

Can anyone advise on what im doing wrong here?
I am trying to select a table full of results, some are duplicates, but the timestamp is different, so I want to filter out by the latest date.
I'm using the following sql query but it just keeps throwing up errors?
$sql = "(SELECT *
FROM measrate
WHERE TRANS_TIME = (SELECT MAX(TRANS_TIME) FROM measrate)";
First, the initial parenthesis should be unnecessary:
SELECT m.*
FROM measrate m
WHERE TRANS_TIME = (SELECT MAX(TRANS_TIME) FROM measrate m2);
Second, if you want only the max time for some group -- say based on the column result -- then modify this to be a correlated subquery:
SELECT m.*
FROM measrate m
WHERE TRANS_TIME = (SELECT MAX(TRANS_TIME) FROM measrate m2 WHERE m2.result= m.result);
sql = "(SELECT * FROM measrate WHERE TRANS_TIME = (SELECT MAX(TRANS_TIME) FROM measrate))";
Forgot last bracket

MySQL select and in where and return two values

I have a two tables, one table has prices, the second table has a priceRangeId, priceRangeMin, priceRangeMax. What I am trying to do is take a priceRangeId and search the first table with the prices that in between the priceRangeMax and PriceRangeMin in my where clause, is this possible?
heres what I got:
$priceRangeId = 1;
SELECT *
FROM `table1`
WHERE price BETWEEN (
SELECT * FROM `table2`
WHERE priceRangeId IN (" . $priceRangeId . ")
ORDER BY `priceRangeMin`
);
but I get this error: You have an error in your SQL syntax
Any help would be much appreciated.
SELECT * FROM `table1`
WHERE price BETWEEN
(SELECT priceRangeMin FROM `table2`
WHERE priceRangeId='$priceRangeId') as min_price
AND (SELECT priceRangeMax FROM `table2`
WHERE priceRangeId='$priceRangeId') as max_price
You could try something like this:
SELECT table1.*
FROM table1, table2
WHERE table2.priceRangeId = $priceRangeId
AND table1.price between table2.PriceRangeMin AND table2.PriceRangeMax
;

SQL Query Syntax error?

I am trying to modify a query which results in 2 records before the modification for some reason my modification makes it not work as it return nothing.
This Query works and returns 2 record:
$query = mysql_query("SELECT * FROM `table1`
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
...the I added this: JOIN table2 USING(id)
...so this final code is this:
$query = mysql_query("SELECT * FROM `table1` JOIN `table2` USING(id)
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
Problem is the second one returns nothing.
Is this a syntax error? How can I get this to work? Both tables have id fields.
Make sure that table2 contains matched data, where the id is equal to the id in table1.
You can use a LEFT JOIN if this match is not required.
id in your ORDER BY is now ambiguous. There might be more errors though. Check with mysql_error()
Try This
$query = mysql_query("SELECT * FROM `table1` a,`table2` b WHERE a.id=b.id
and (`a.date` = '{$eventdate->format('Y-m-d')}' OR `a.date` >= CURDATE())
ORDER BY id DESC")
When joining two tables which have no prefixes on the column names like - table1_id, table2_id, you should use aliases like -
SELECT * FROM table1 as t1 JOIN table2 as t2 on ...
and then you can refer to the fields in the table like this - t1.id, t2.id (you can do this also without aliases( as t1) and then you should refer to the fields like - table1.id).
The problem with your script is that the 2 tables have column id and in :
ORDER BY id DESC
the engine doesn`t know from which table do you refer this id
Other suggestion of mine is when possible not to use aggregation functions in the queries(in your query the CURDATE is that type of function). Aggregation functions in SQL prevent query caching. In our case you can pass the currdate from php to the query and the query can be cached.
Hope i`ve helped.

SQL Query - Subquery returns more than one row

Table:
laterecords
-----------
studentid - varchar
latetime - datetime
reason - varchar
My Query:
SELECT laterecords.studentid,
laterecords.latetime,
laterecords.reason,
( SELECT Count(laterecords.studentid) FROM laterecords
GROUP BY laterecords.studentid ) AS late_count
FROM laterecords
I'm getting " MySQL Subquery Returns more than one row" error.
I know a workaround for this query to use the following query:
SELECT laterecords.studentid,
laterecords.latetime,
laterecords.reason
FROM laterecords
Then using php loop to though the results and do below query to get the late_count and echo it out:
SELECT Count(laterecords.studentid) AS late_count FROM laterecords
But i think there might be a better solution ?
The simple fix is to add a WHERE clause in your subquery:
SELECT
studentid,
latetime,
reason,
(SELECT COUNT(*)
FROM laterecords AS B
WHERE A.studentid = B.student.id) AS late_count
FROM laterecords AS A
A better option (in terms of performance) is to use a join:
SELECT
A.studentid,
A.latetime,
A.reason,
B.total
FROM laterecords AS A
JOIN
(
SELECT studentid, COUNT(*) AS total
FROM laterecords
GROUP BY studentid
) AS B
ON A.studentid = B.studentid

Categories