Trying to figure out if there is a MySQL query for the following scenario:
Database example
id---fruit------date
01---apple------1990-01-01
02---banana-----2020-01-01
03---orange-----2021-02-03
04---apple------1999-12-12
05---pear-------2009-01-02
06---apple------2008-09-18
07---banana-----2007-11-12
I want a query to return all rows but for rows with the same fruit only one occurence and preferably the occurence with the latest date. So based on the above the query would return:
id---fruit------date
02---banana-----2020-01-01
03---orange-----2021-02-03
05---pear-------2009-01-02
06---apple------2008-09-18
SELECT * FROM `table_name`
WHERE
id
IN
(
SELECT SUBSTRING_INDEX(temp,"|",1) `id` FROM
(
SELECT *,GROUP_CONCAT(id ORDER BY DATE DESC SEPARATOR "|") temp FROM `table_name`
GROUP BY fruit
)
AS dbx
)
Explaination:
Group_concat Id with Order by date. At this time I user separator "|"
Get position of that char to return latest ID
Select again from that table
Related
I have these records in a MySQL DB. On a JSON type column.
Record1: {"images": ["image.jpeg", "image.jpeg"]}
Record2: {"images": ["image.jpeg", "image.jpeg", "image.jpeg"]}
Record3: {"images": ["image.jpeg"]}
How can I get the total count of images by the key name of the JSON property which in my case is 'images'?
I am trying to achieve the same thing as running this below query, but counting the array items from the images key.
SELECT
`field`,
count( * ) AS total
FROM
`table_name`
WHERE
`condition`
GROUP BY
`something`
which will give you this result:
field total
------------------
field1 5
field2 2
What I am trying to achieve:
field total
-----------------
images 6
Table structure
Table data
Try:
SELECT
`type`,
SUM(
JSON_LENGTH(`media`, '$.images')
) `media`
FROM
`table_name`
GROUP BY
`type`;
See dbfiddle.
ok sure You can use this query :
SELECT type,JSON_LENGTH(media) FROM `tabl4` group by type
check the execution from here : Demo
I need to get data from MySQL table in ascending order but zero values come last and randomly
Right now this is my order by condition.This is not working
ORDER BY sortorder=0 RAND(),sortorder
Use conditional ordering
select *
from table
order by column > 0 desc, column asc, rand()
Add rand() at the end
Demo
Or you could use union
(select * from table where column > 0 order by column asc)
union all
(select * from table where column = 0 order by rand())
Demo
If you want to get data from mysql randomly and zero values come last. You may want to try the following:
SELECT * FROM table ORDER BY `column` = 0, rand();
I have an Oracle query that currently display all of my data
$qu = 'SELECT * FROM baan.tcbpur012777 WHERE T$RQNO LIKE :bagian GROUP BY tcbpur012777.T$RQNO ORDER BY T$RQNO OFFSET '.$start.' ROWS FETCH NEXT '.$perPage.' ROWS ONLY';
$r = oci_parse($conn, $qu);
oci_bind_by_name($r,':bagian',$bag);
oci_execute($r);
$n = oci_fetch_all($r, $q);
What i wanna do is group the duplicated data into one,But Every time i use group by syntax, warning will appear and make my syntax invalid.
Warning: oci_fetch_all(): ORA-24374: define not done before fetch or execute and fetch in
Can anybody please tell me what's wrong with my syntax??
Thanks in advance
You are doing:
SELECT *
FROM table_name
GROUP BY column_name
You need to either include all the columns in the GROUP BY clause or, for each column not in the GROUP BY clause you need to use an aggregation function to aggregate it over the group. Assuming your table has more than one column then SELECT * will get all those columns but GROUP BY column_name is only grouping by one of the columns and the other columns are not part of an aggregation so it will throw an ORA-00979 not a group by expression exception.
Something like:
SELECT T$RQNO,
MAX( Col1 ) AS MaxCol1,
MIN( Col2 ) AS MinCol2,
LISTAGG( Col3, ',' ) WITHIN GROUP ( ORDER BY Col4 ) AS ListOfCol3
FROM baan.tcbpur012777
WHERE T$RQNO LIKE :bagian
GROUP BY T$RQNO
ORDER BY T$RQNO
OFFSET '.$start.' ROWS
FETCH NEXT '.$perPage.' ROWS ONLY
I am trying to get a result where a single column id is like a comma separated columns, my two table are as follows:
Room Location Table
Events Table
User Table
My query is
$sql=" SELECT users.*, events.*, room_location.*
FROM events
INNER JOIN room_location ON events.event_room = room_location.location
INNER JOIN users ON room_location.user_loc_id = users.userlocationaccess
WHERE room_location.user_loc_id LIKE '%1,2%'";
$result = $conn->query($sql);
The query above works if I use single id in in the users->userGroupLocID.
How do I amend my query to work so it find if the id is like my comma separated columns?
You can search a CSV field using FIND_IN_SET(str,strlist) function.
Example:
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
Documentation Says:
Returns a value in the range of 1 to N if the string str is in the
string list strlist consisting of N substrings. A string list is a
string composed of substrings separated by “,” characters.
You can pass users location id to find in the column userGroupLocID
select find_in_set( location_id_in_search, replace( userGroupLocID, ' ', '' ) )
from table_name;
I know that this must be a very basic question, but I've not found an answer.
As the title says, I would like the query the record that holds the max value of a specific column.
I use the following code to achieve that:
SELECT * FROM `table_name` ORDER BY `column_with_specific_max_value` DESC LIMIT 1
I would like to know if there is an other way to achieve the same result (more parsimonious)? I know that SQL has a function MAX(column) but it's not working the way I want. I tried this:
SELECT * FROM `table_name` WHERE `column_with_specific_max_value`=MAX(`column_with_specific_max_value`)
and this:
SELECT *, MAX(`column_with_specific_max_value`) FROM `table_name`
What happen if the column_with_specific_max_value has 2 rows with the same max value? will it return both rows?
What about?
select * from table1
where score in (select max(score) from table1)
Or even without a max:
select * from table1
where score >= all (select score from table1)
Any of those WILL return all rows with the max value. You can play with it here.
If your table has an auto-increment column to work with, you could do something like...
select
YT3.*
from
( select
MAX( YT2.AutoIncColumn ) as ReturnThisRecordID
from
( select max( YT1.WhatColumn ) as MaxColumnYouWant
from YourTable YT1 ) JustMax
Join YourTable YT2
on JustMax.MaxColumnYouWant = YT2.WhatColumn ) FinalRecord
JOIN YourTable YT3
on FinalRecord.ReturnThisRecordID = YT3.AutoIncColumn
I would also ensure this is a column that SHOULD have an index on it, otherwise, you'll always be doing a table scan.