Mysql select ordinal - mysql

Having a table named books which has the following structure:
╔════════════╦═══════════╦════════╗
║ LibraryId ║ BookId ║ Price ║
╠════════════╬═══════════╬════════╣
║ 123 ║ 9001 ║ 10.99 ║
║ 123 ║ 9005 ║ 12.99 ║
║ 123 ║ 9006 ║ 7.99 ║
║ 124 ║ 8012 ║ 6.49 ║
║ 124 ║ 9001 ║ 3.19 ║
║ 124 ║ 9076 ║ 7.39 ║
╚════════════╩═══════════╩════════╝
How could I do a select that would return the full table, but additionally a field named Ordinal, that "counts" the number of books per library. The result should look something like:
╔════════════╦═══════════╦════════╦════════╗
║ LibraryId ║ BookId ║ Price ║Ordinal ║
╠════════════╬═══════════╬════════╬════════╣
║ 123 ║ 9001 ║ 10.99 ║ 1 ║
║ 123 ║ 9005 ║ 12.99 ║ 2 ║
║ 123 ║ 9006 ║ 7.99 ║ 3 ║
║ 124 ║ 8012 ║ 6.49 ║ 1 ║
║ 124 ║ 9001 ║ 3.19 ║ 2 ║
║ 124 ║ 9076 ║ 7.39 ║ 3 ║
╚════════════╩═══════════╩════════╝════════╝
I have tried something like:
SET #var_record = 1;
SELECT *, (#var_record := #var_record + 1) AS Ordinal
FROM books;
But this will continue counting irrespective of the libraryId. I need something that will reset the ordinal every time the libraryId changes. I'd prefer a single query instead of procedures.
Test data sql scripts:
create temporary table books(libraryId int, bookId int, price double(4,2));
insert into books (libraryId, bookId, price) values (123, 9001, 10.99),(123, 9005, 10.99),(123, 9006, 10.99),(124, 8001, 10.99),(124, 9001, 10.99),(124, 9076, 10.99);

Using variables and conditions you can reset the counter based on a condition (libraryId has changed). Mandatory to order by the column libraryId.
SELECT books.*,
if( #libId = libraryId,
#var_record := #var_record + 1,
if(#var_record := 1 and #libId := libraryId, #var_record, #var_record)
) AS Ordinal
FROM books
JOIN (SELECT #var_record := 0, #libId := 0) tmp
ORDER BY libraryId;
The second if statement is used to group two assignments together and return #var_record.
if(#var_record := 1 and #libId := libraryId, #var_record, #var_record)

perhaps you can use aggregated functions
SELECT a.LibraryId, a.BookId, a.Price,
(SELECT COUNT(b.BookId) FROM books b WHERE b.BookId = a.BookId AND b.LibraryId = a.LibraryId) AS Ordinal
FROM a.books

Related

Mysql Update column with subrequest Order By

I have a table biblek2 items with those 4 columns :
id (autoincrement)
catid(int)
introtext(varchar)
ordering(int)
Table biblek2_items
╔════╦═══════╦═══════════╦══════════╗
║ ID ║ catid ║ introtext ║ ordering ║
╠════╬═══════╬═══════════╬══════════╣
║ 1 ║ 3024 ║ orange ║ 122 ║
║ 2 ║ 2024 ║ zebra ║ 45 ║
║ 3 ║ 3010 ║ juice ║ 55 ║
║ 4 ║ 3002 ║ build ║ 17 ║
║ 5 ║ 2003 ║ car ║ 87 ║
║ 6 ║ 1610 ║ other ║ 1521 ║
║ 7 ║ 1620 ║ other ║ 200 ║
╚════╩═══════╩═══════════╩══════════╝
I expect that
Table biblek2_items
╔════╦═══════╦═══════════╦══════════╗
║ ID ║ catid ║ introtext ║ ordering ║
╠════╬═══════╬═══════════╬══════════╣
║ 5 ║ 2003 ║ car ║ 1 ║
║ 4 ║ 3002 ║ build ║ 2 ║
║ 3 ║ 3010 ║ juice ║ 3 ║
║ 1 ║ 3024 ║ orange ║ 4 ║
║ 2 ║ 2024 ║ zebra ║ 5 ║
╚════╩═══════╩═══════════╩══════════╝
I want to
select * from biblek2_items where catid between 2001 and 3024
ORDER BY introtext ASC
empty the ordering column
reorder the ordering column by increment from 1 to n according to the result of the order column
I tried this with no success
DECLARE #variable int
SET #variable = 0
UPDATE `biblek2_items`
SET #variable = ordering = #variable + 1
WHERE ordering IN (SELECT ordering
FROM `biblek2_items`
WHERE catid BETWEEN 2001 AND 3024
ORDER BY `introtext` DESC)
I read in the forum that MySQL can't allow subrequests with ORDER BY, so could you help me
As explained in the comments :
The ORDER BY in your sub query makes no sense anyway, because, you don't LIMIT. So all rows will be returned and it doesn't matter how they are ordered because all of them are taken into account with the IN in your main query.
But there are other issues with your query.
Do this instead :
SET #row_number = 0 ;
UPDATE biblek2_items,
(select id, catid,introtext,ordering, (#row_number:=#row_number + 1) AS newordering
from biblek2_items
where catid between 2001 and 3024
ORDER BY introtext ASC
) as temp
SET biblek2_items.ordering = temp.newordering
WHERE biblek2_items.ID = temp.ID
Additionally, if you have a large table, and a lot of users actively writing on it, to avoid inconsistencies or locking issues, I would suggest a slightly different method, using a temporary table to store the computed new ordering.
CREATE TABLE biblek2_items_TEMP (ID INT, ordering INT);
SET #row_number = 0 ;
INSERT INTO biblek2_items_TEMP
select id, (#row_number:=#row_number + 1) AS newordering
from biblek2_items
where catid between 2001 and 3024
ORDER BY introtext ASC
;
UPDATE biblek2_items, biblek2_items_TEMP
SET biblek2_items.ordering = biblek2_items_TEMP.ordering
WHERE biblek2_items.ID = biblek2_items_TEMP.ID;
DROP TABLE biblek2_items_TEMP;
Tested successfully on MySQL 5.7 and MariaDB 10

Path from a group

I have the following data:
╔════╦═══════╦═══════╗
║ id ║ group ║ place ║
╠════╬═══════╬═══════╣
║ 1 ║ 1 ║ a ║
║ 2 ║ 1 ║ b ║
║ 3 ║ 1 ║ b ║
║ 4 ║ 1 ║ a ║
║ 5 ║ 1 ║ c ║
║ 6 ║ 2 ║ a ║
║ 7 ║ 2 ║ b ║
║ 8 ║ 2 ║ c ║
╚════╩═══════╩═══════╝
How can I get the path of each group in MySQL?
The expected result is:
╔═══════╦════════════╗
║ group ║ path ║
╠═══════╬════════════╣
║ 1 ║ a-b-a-c ║
║ 2 ║ a-b-c ║
╚═══════╩════════════╝
Assuming that the end goal is to sort by group and id, and then simplify each group's sequence so that consecutive repeated places are only shown once:
Start by determining, for each row, whether the place or the group have changed since the previous row. There's a good solution to this problem in this answer.
Then use GROUP_CONCAT to merge the places together into a path.
Be aware that GROUP_CONCAT has a user-configurable maximum length, which by default is 1,024 characters.
SELECT
`group`,
GROUP_CONCAT(place ORDER BY id SEPARATOR '-') path
FROM
(SELECT
COALESCE(#place != place OR #group != `group`, 1) changed,
id,
#group:=`group` `group`,
#place:=place place
FROM
place_table, (SELECT #place:=NULL, #group:=NULL) s
ORDER BY `group`, id) t
WHERE
changed = 1
GROUP BY `group`;

MySql Query for identifying sequence in a table

I Need help with mysql query to update a new column of the same table based on series of entry and exit dates.
Below is table:
╔════╦═══════════╦═════════════╦═════════════╦════════════════════╗
║ ID ║ PLACE ║ ENTRYDATE ║ EXITDATE ║ LAST_PLACE_VISITED ║
╠════╬═══════════╬═════════════╬═════════════╬════════════════════╣
║ 1 ║ Delhi ║ 1-Jan-2012 ║ 5-Jan-2012 ║ ║
║ 1 ║ Agra ║ 10-Jan-2012 ║ 11-Jan-2012 ║ ║
║ 1 ║ Bangalore ║ 21-Jan-2012 ║ 24-Jan-2012 ║ ║
║ 1 ║ Mumbai ║ 12-Jan-2012 ║ 19-Jan-2012 ║ ║
║ 2 ║ LA ║ 1-Mar-2012 ║ 3-Mar-2012 ║ ║
║ 2 ║ SFO ║ 10-Mar-2012 ║ 14-Mar-2012 ║ ║
║ 2 ║ NY ║ 4-Mar-2012 ║ 9-Mar-2012 ║ ║
║ 3 ║ Delhi ║ 12-Apr-2012 ║ 13-Apr-2012 ║ ║
╚════╩═══════════╩═════════════╩═════════════╩════════════════════╝
The data type of ENTRYDATE and EXITDATE is DATE.
From the above table i need to write a query to update "Last_Place_Visited" column based on entry and exit date of the ID.
Any help with this query would be much appriciated.
Thanks.
Bhargav
Here's a very messy one since MySQL doesn't support window functions,
UPDATE TravelTbl a
INNER JOIN
(
SELECT a.ID,
a.Place,
a.EntryDate,
a.ExitDate,
b.Place Last_Place_Visited
FROM
(
SELECT ID,
Place,
EntryDate,
ExitDate,
Last_Place_Visited,
#grp := if(#ID = ID, #grp ,0) + 1 GRP_RecNo,
#ID := ID
FROM TravelTbl,
(SELECT #ID := '', #grp := 0) vars
ORDER BY EntryDate
) a
LEFT JOIN
(
SELECT ID,
Place,
EntryDate,
ExitDate,
Last_Place_Visited,
#grp2 := if(#ID2 = ID, #grp2 ,0) + 1 GRP_RecNo,
#ID2 := ID
FROM TravelTbl,
(SELECT #ID2 := '', #grp2 := 0) vars
ORDER BY EntryDate
) b ON a.ID = b.ID AND
a.GRP_RecNo = b.GRP_RecNo + 1
) b ON a.ID = b.ID AND
a.Place = b.Place AND
a.EntryDate = b.EntryDate AND
a.ExitDate = b.ExitDate AND
b.Last_Place_Visited IS NOT NULL
SET a.Last_Place_Visited = b.Last_Place_Visited
SQLFiddle Demo
OUTPUT
╔════╦═══════════╦═════════════╦═════════════╦════════════════════╗
║ ID ║ PLACE ║ ENTRYDATE ║ EXITDATE ║ LAST_PLACE_VISITED ║
╠════╬═══════════╬═════════════╬═════════════╬════════════════════╣
║ 1 ║ Delhi ║ 1-Jan-2012 ║ 5-Jan-2012 ║ (null) ║
║ 1 ║ Agra ║ 10-Jan-2012 ║ 11-Jan-2012 ║ Delhi ║
║ 1 ║ Bangalore ║ 21-Jan-2012 ║ 24-Jan-2012 ║ Mumbai ║
║ 1 ║ Mumbai ║ 12-Jan-2012 ║ 19-Jan-2012 ║ Agra ║
║ 2 ║ LA ║ 1-Mar-2012 ║ 3-Mar-2012 ║ (null) ║
║ 2 ║ SFO ║ 10-Mar-2012 ║ 14-Mar-2012 ║ NY ║
║ 2 ║ NY ║ 4-Mar-2012 ║ 9-Mar-2012 ║ LA ║
║ 3 ║ Delhi ║ 12-Apr-2012 ║ 13-Apr-2012 ║ (null) ║
╚════╩═══════════╩═════════════╩═════════════╩════════════════════╝
I tried to modify the table itself:
UPDATE T SET LAST_PLACE_VISITED = (
SELECT t2.PLACE
FROM T t2
WHERE t2.EXITDATE = (
SELECT MAX(t1.EXITDATE)
FROM T t1
WHERE t1.ID = ID
AND t1.EXITDATE < EXITDATE
));
MySQL won't permit this:
You can't specify target table 'T' for update in FROM clause:
But you could work with a view or a temporary table and use this:
UPDATE: Inserted LIMIT 1 for dealing with the case of multiple occurences of the maximum value of EXITDATE for distinct IDs. Disadvantage: We cannot predict which row with maximum value will be taken.
UPDATE 2: Added condition AND t2.ID = t0.ID
SELECT t0.ID, t0.PLACE, t0.ENTRYDATE, t0.EXITDATE, (
SELECT t2.PLACE
FROM T t2
WHERE t2.EXITDATE = (
SELECT MAX(t1.EXITDATE)
FROM T t1
WHERE t1.ID = t0.ID
AND t1.EXITDATE < t0.EXITDATE
)
AND t2.ID = t0.ID
LIMIT 1
) AS LAST_PLACE_VISITED
FROM T t0;
See my SQLFiddle demo

MySQl query Select all rows with same value in limit so that no value is left outside the limit defined

╔════════╦═══════════╦═══════╗
║ MSG_ID ║ RANDOM_ID ║ MSG ║
╠════════╬═══════════╬═══════╣
║ 1 ║ 22 ║ apple ║
║ 2 ║ 22 ║ bag ║
║ 3 ║ 0 ║ cat ║
║ 4 ║ 0 ║ dog ║
║ 5 ║ 0 ║ egg ║
║ 6 ║ 21 ║ fish ║
║ 7 ║ 21 ║ hen ║
║ 8 ║ 20 ║ glass ║
╚════════╩═══════════╩═══════╝
Want to fetch 3 records in a lot such a way that all the data of a particular random_id is picked up .
Result Required:
║ MSG_ID ║ RANDOM_ID ║ MSG ║
╠════════╬═══════════╬═══════╣
║ 1 ║ 22 ║ apple ║
║ 2 ║ 22 ║ bag ║
║ 3 ║ 0 ║ cat ║
Current Result:
║ MSG_ID ║ RANDOM_ID ║ MSG ║
╠════════╬═══════════╬═══════╣
║ 1 ║ 22 ║ apple ║
║ 3 ║ 0 ║ cat ║
║ 4 ║ 0 ║ dog ║
______________________________
Query Used:
SELECT ID,Random_ID, GROUP_CONCAT(message SEPARATOR ' ' ),FLAG,mobile,sender_number,SMStype
FROM messagemaster
WHERE Random_ID > 0
GROUP BY Random_ID
UNION
SELECT ID,Random_ID, message,FLAG,mobile,sender_number,SMStype
FROM messagemaster
WHERE Random_ID = 0
order by random_id LIMIT 100;
I don't want to pick up records using group by.I want to fetch all the records w rt random_ids .Like , if there is a random_id for which there are 3 records and if the query has limit =3 , then i want all the data w r t those random_id to be picked up.
The situation is if I fetch rows with limit 100 , i dont want that some of the data with the random id present in the result set is not picked.
For example if i am picking records limit by 3 then for random id=22 , all records with random id =22 should be picked .
Consider the following...
SELECT b.*
FROM
( SELECT x.*, SUM(y.cnt)
FROM
( SELECT random_id,COUNT(*) cnt FROM messagemaster GROUP BY random_id) x
JOIN
( SELECT random_id,COUNT(*) cnt FROM messagemaster GROUP BY random_id) y
ON y.random_id >= x.random_id
GROUP
BY x.random_id
HAVING SUM(y.cnt) < 4
) a
JOIN messagemaster b
ON b.random_id = a.random_id;

Fetching Latest Record from MySQL for each individual

I have a table like this
╔════╦════════╦═════════════╦═════════════════╗
║ PK ║ NAME ║ DEGREE ║ YEAR_OF_PASSING ║
╠════╬════════╬═════════════╬═════════════════╣
║ 1 ║ Shrey ║ B.E. ║ 2004 ║
║ 2 ║ Shrey ║ High School ║ 2000 ║
║ 3 ║ Gaurav ║ B.E. ║ 2000 ║
║ 4 ║ Gaurav ║ M.Sc. ║ 2002 ║
╚════╩════════╩═════════════╩═════════════════╝
How do I query to get a resultset of latest degree of each person as shown below?
╔════╦════════╦════════╦═════════════════╗
║ PK ║ NAME ║ DEGREE ║ YEAR_OF_PASSING ║
╠════╬════════╬════════╬═════════════════╣
║ 1 ║ Shrey ║ B.E. ║ 2004 ║
║ 4 ║ Gaurav ║ M.Sc. ║ 2002 ║
╚════╩════════╩════════╩═════════════════╝
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT Name, MAX(Year_Of_Passing) max_val
FROM tableName
GROUP BY Name
) b ON a.name = b.name AND
a.Year_Of_Passing = b.max_val
SQLFiddle Demo
UPDATE 1
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT Name, MAX(Year_Of_Passing) max_val, MAX(PK) max_pk
FROM tableName
GROUP BY Name
) b ON a.name = b.name AND
CASE WHEN b.max_val IS NULL
THEN a.pk = max_PK
ELSE a.Year_Of_Passing = b.max_val
END
SQLFiddle Demo