0

I've got a text field called source_recid. It stores half string half number like strings in it.

Example

shop.orders.32442

the syntax is DATABASENAME.TABLENAME.RECID

My goal is to scan this col and find out the biggest RECID ( the integer) in it.

So, in a case like this

shop.orders.32442
shop.orders.82000
shop.orders.34452

It would be the record whose source_recid is shop.orders.82000. Why? Cause 82000 happens to be the largest integer.

What SQL statement would get me that record?

One option to this is to create a new column ( the_ids ) and move all the integers in it and then run something like this

select source_recid from mytable 
  where source_recid like 'shop.orders.%' 
    order by the_ids DESC 
     LIMIT 1

Is there a way to pull this off without going thru this step?

2 Answers 2

1

First of all, unless all of your RECIDs are exactly five characters long forever and always, the select you put up won't work, becuase "shop.order.9" would come out as larger than "shop.order.10", which is wrong.

What I think we need to do here is extract the numeric part, cast it to an integer, and sort by that. Now, I don't have access to mySQL, so this may not be exactly right, but it should be close ...

SELECT
    CAST(SUBSTRING_INDEX(RECID,'.',-1) AS INT) AS RecIdNumber
FROM
    table
WHERE
    RECID LIKE 'shop.order.%'
ORDER BY
    RecIdNumber DESC
LIMIT
    0, 1

This will take the part after the last dot, convert it to an INT, name it 'RecIdNumber', and sort by that.

I hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

select max(cast(substring_index(source_recid,'.',-1) as unsigned)) from table;
Thanks to all. But the only one worked was Tim's. I was getting an error around integer or it was not giving me the number. for some reason, Tim's worked., So, Tim, please submit your comment as answer so I chose it.
1
SELECT CAST(SUBSTRING_INDEX(field,'.',-1) AS INT) AS RID
FROM yourtable
WHERE
RECID LIKE 'shop.order.%'
ORDER BY
RID DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.