I have a table which contains a column called ticket_id and it contains values as follows:
ticket_id
STK0000000001
STK0000000002
STK0000000001
STK0000000003
STK0000000002
STK0000000001
The ticket_id value will repeat in certain rows, so it is not unique.
I am using this query to get the next available id, but I am not able to get it working. It always returns STK0000000002.
Any help is appreciated!
SQL:
SELECT
CONCAT('STK', LPAD(seq, 10, '0')) AS nextID
FROM
(SELECT
#seq:=#seq+1 AS seq,
num
FROM
(SELECT
CAST(SUBSTR(ticket_id, 4) AS UNSIGNED) AS num
FROM
sma_support_tickets
UNION ALL
SELECT
MAX(CAST(SUBSTR(ticket_id, 4) AS UNSIGNED))+2 AS num
FROM
sma_support_tickets
ORDER BY
num) AS ids
CROSS JOIN
(SELECT #seq:=0) AS init
) AS pairs
WHERE
seq!=num
LIMIT 1
Maybe I'm missing something in your question, but it seems that this should do it:
SELECT CONCAT('STK',
LPAD(MAX(SUBSTRING(ticket_id, 4)) + 1,
10,
'0')
)
FROM sma_support_tickets;
Try: This table must have one serial number or unique number or ID for the table for each row. Find out that unique number(primary key) through code and add 1 or increment that number, but not to the ticket_id as you are doing it now. so that it can move forward to next row.
Related
I am looking for the most efficient way to find the next or previous ID of the following query:
SELECT *
FROM transactions
ORDER
BY CASE order_status
WHEN 'order_accepted' THEN 1
WHEN 'processing_order' THEN 2
WHEN 'order_send_mailer' THEN 3
WHEN 'order_send' THEN 4
WHEN 'order_received' THEN 5
WHEN 'order_refunded' THEN 6
ELSE 7 END
, id DESC limit 1;
I tried adding a where id > '$id' or where id < '$id' claus to the query but it didn't give me te next or previous ID I was looking for.
For those that need some explanation of what I am trying to do: It's to go to the next or previous order by case with a forward of backward button.
What it currently looks like:
-id- -order_status-
9399 order_accepted
9398 processing_order
9363 processing_order
9403 order_send_mailer
9318 order_send
9346 order_received
9345 order_received
9050 order_refunded
The next ID for example of 9403 would be 9363 and previous ID would be 9318
Change your order_status into an enum column. This will save disk space and make sorting by order_status simpler and faster.
-- Add a new version of the column using an enum.
-- These strings are aliases for ordered numbers.
-- 'order_accepted' is 1, 'processing_order' is 2, etc.
alter table transactions add column enum_order_status enum(
'order_accepted',
'processing_order',
'order_send_mailer',
'order_send',
'order_received',
'order_refunded'
) not null;
-- Copy the status into the new enum column.
-- MySQL will translate the string into the number for you.
update transactions
set enum_order_status = order_status;
-- Drop the old column.
alter table transactions drop column order_status;
-- Rename the new enum column.
alter table transactions rename column enum_order_status to order_status;
-- Index it.
create index transactions_order_status on transactions(order_status);
-- Enjoy your vastly simplified and much faster query.
select *
from transactions
order by order_status, id desc
That's not actually necessary, but it makes everything much simpler.
With that out of the way, use the window functions lead and lag to refer to the previous and next rows in a query.
select
id, order_status,
lead(id) over w, lead(order_status) over w,
lag(id) over w, lag(order_status) over w
from transactions
window w as (order by order_status, id desc);
Note, window functions were added in MySQL 8. If you're using an older version I recommend upgrading ASAP; MySQL 8 has many big improvements. Otherwise you can simulate it with correlated subqueries and self-joins.
If you want the previous and next rows of a specific row, use the technique from this answer. We add row_numbers to the table in the desired order, and then fetch 9403 and its previous and next row by row number.
-- Add a row number to your table in the desired order.
with ordered_transactions as (
select
*, row_number() over w as rn
from transactions
window w as (order by order_status, id desc)
)
select *
from ordered_transactions
-- Find the row number for ID 9403, then add -1, 0, and 1.
-- If 9403 is row number 5 you'll fetch row numbers 4, 5, and 6.
where ot.rn in (
select rn+i
from ordered_transactions ot
-- All this is doing is making us three "rows" where i = -1, 0, and 1.
cross join (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) cj
where ot.id = 9403
);
Try it.
Given table can have following rows.
i.e. for a given filename, there can be two unique version_id(s).
file_id version_id filename
1 OS_v1 abc.update
1 App_v1 abc.update
2 OS_v2 xyz.update
2 App_v2 xyz.update
3 OS_v1 abc(1).update
3 App_v1 abc(1).update
PRIMARY KEY (`version_id`, `filename`)
How to detect there are no two different filename's having same combination of OS_App (versions) ?
In the given example, row set with file_id=3 is a duplicate of file_id=1.
Note: It's easy to define separate columns for OS and App version, but that requires a lot of code change which we dont wanted to go through.
Question: is there a SELECT query which would return just file_id = 1 and file_id = 2 and omit file_id = 3 ?
So far I have come up with this query which selects a combination of version_id grouped by filename, but row-2 is a duplicate of row-1
SELECT DISTINCT(GROUP_CONCAT(version_id SEPARATOR '-')) ,
filename
FROM schema_name.table_name
GROUP BY filename;
Returns :
concat_version patch_filename
OS_V1-APP_V1 xyz.update
OS_V2-APP_V2 abc(1).update
OS_V1-APP_V1 abc.update
Question: Is there a SELECT query which would return just file_id = 1 and file_id = 2 and omit file_id = 3
If you are using MySQL 8.0, you can take advantage of window function ROW_NUMBER() :
SELECT x.file_id, x.version_id, x.filename
FROM (
SELECT t.*, ROW_NUMBER() OVER(PARTITION BY version_id ORDER BY file_id) rn
FROM master_logs.system_patches t
) x
WHERE x.rn = 1
The inner query assigns a row number to each record in version_id groups, ordered by file_id, and the outer query filters in records with row number 1.
With earlier versions of MySQL, one typical solution is to use a correlated subquery with a NOT EXISTS condition to filter out unwanted records :
SELECT t.file_id, t.version_id, t.filename
FROM master_logs.system_patches t
WHERE NOT EXISTS (
SELECT 1
FROM master_logs.system_patches t1
WHERE t1.version_id = t.version_id AND t1.file_id < t.file_id
)
I need to generate unique "ids", the catch is, it can be only between 1 - 99999.
The "good" thing is, that it has to be unique only in group with another column.
We have groups, each group has its own "group_id" and each group need something like unique('group_id', 'increment_id')
The 99999 records is enough for several years for each group right now, but it is not enough for all groups together, therefore I cant just create table with AUTO_INCREMENT and inserting there records and taking its auto increment.
For example, if I need 5 records for Group one and three records for Group two, I suppose to get something like this:
group_id, increment_id
1, 1,
1, 2,
1, 3,
1, 4,
1, 5,
2, 1
2, 2,
2, 3
Also, the conflict is not an option, therefore using something like "length" can be tricky, if done programatically (there can be i.e. 10 requests at once, each of them first select length for given group_id and then tries to create 10 rows with same increment_id)
However I am thinking - if I set it up as the value of subselect of count, than it will always be "ok"?
You can create a auxiliar table named counters to manage that:
table: counters
columns: group_id, current_counter
OR
Each time you insert a row increment_id = select max(increment_id)+1 from table_xxx where group_id = group_xxxx
You can use user variables to get the incrementing number within each group_id:
select
t.*,
#rn := if(#group_id = group_id,
#rn + 1,
if(#group_id := group_id, 1, 1)
) increment_id
from (
select group_id
from your_table t
/* some where clauses */
order by group_id
) t
cross join (
select #rn := 0,
#group_id := - 1
) t2
I need to find the next available ID on a table that has keys that are strings. I have followed an example here. My example below:
Dishes Table (first columns)
Table_id
DSH0000000003
DSH0000000004
DSH0000000005
DSH0000000007
SQL:
SELECT CONCAT('DSH',LPAD(MIN(SUBSTRING(t1.dish_id FROM 4) + 1), 10, '0')) AS nextID
FROM dishes t1
WHERE NOT EXISTS (SELECT t2.dish_id
FROM dishes t2
WHERE SUBSTRING(t2.dish_id FROM 4) = SUBSTRING(t1.dish_id FROM 4) + 1)
Output:
DSH0000000006
If I delete #5 then it returns #5 but it does not return "DSH0000000001".
You may use variables to build consecutive ids, then compare where's first non-matched id:
SELECT
CONCAT('DSH', LPAD(seq, 10, '0')) AS k
FROM
(SELECT
#seq:=#seq+1 AS seq,
num
FROM
(SELECT
CAST(SUBSTR(table_id, 4) AS UNSIGNED) AS num
FROM
t
UNION ALL
SELECT
MAX(CAST(SUBSTR(table_id, 4) AS UNSIGNED))+2 AS num
FROM
t
ORDER BY
num) AS ids
CROSS JOIN
(SELECT #seq:=0) AS init
) AS pairs
WHERE
seq!=num
LIMIT 1
Fiddle is available here.
You should add a test of your start value. With your current approach you can only get values greater than the minimum value that exists in your table.
You could use IF() to distinguish the two possibilities.
I'd like to use a single SQL query (in MySQL) to find the record which comes after one that I specify.
I.e., if the table has:
id, fruit
-- -----
1 apples
2 pears
3 oranges
I'd like to be able to do a query like:
SELECT * FROM table where previous_record has id=1 order by id;
(clearly that's not real SQL syntax, I'm just using pseudo-SQL to illustrate what I'm trying to achieve)
which would return:
2, pears
My current solution is just to fetch all the records, and look through them in PHP, but that's slower than I'd like. Is there a quicker way to do it?
I'd be happy with something that returned two rows -- i.e. the one with the specified value and the following row.
EDIT: Sorry, my question was badly worded. Unfortunately, my definition of "next" is not based on ID, but on alphabetical order of fruit name. Hence, my example above is wrong, and should return oranges, as it comes alphabetically next after apples. Is there a way to do the comparison on strings instead of ids?
After the question's edit and the simplification below, we can change it to
SELECT id FROM table WHERE fruit > 'apples' ORDER BY fruit LIMIT 1
SELECT * FROM table WHERE id > 1 ORDER BY id LIMIT 1
Even simpler
UPDATE:
SELECT * FROM table WHERE fruit > 'apples' ORDER BY fruit LIMIT 1
So simple, and no gymnastics required
Select * from Table
where id =
(Select Max(id) from Table
where id < #Id)
or, based on the string #fruitName = 'apples', or 'oranges' etc...
Select * from Table
where id =
(Select Max(id) from Table
where id < (Select id from Table
Where fruit = #fruitName))
I'm not familiar with the MySQL syntax, but with SQL Server you can do something with "top", for example:
SELECT TOP 1 * FROM table WHERE id > 1 ORDER BY id;
This assumes that the id field is unique. If it is not unique (say, a foreign key), you can do something similar and then join back against the same table.
Since I don't use MySQL, I am not sure of the syntax, but would imagine it to be similar.
Unless you specify a sort order, I don't believe the concepts of "previous" or "next" are available to you in SQL. You aren't guaranteed a particular order by the RDBMS by default. If you can sort by some column into ascending or descending order that's another matter.
This should work. The string 'apples' will need to be a parameter.
Fill in that parameter with a string, and this query will return the entire record for the first fruit after that item, in alphabetical order.
Unlike the LIMIT 1 approach, this should be platform-independent.
--STEP THREE: Get the full record w/the ID we found in step 2
select *
from
fruits fr
,(
--STEP TWO: Get the ID # of the name we found in step 1
select
min(vendor_id) min_id
from
fruits fr1
,(
--STEP ONE: Get the next name after "apples"
select min(name) next_name
from fruits frx
where frx.name > 'apples'
) minval
where fr1.name = minval.next_name
) x
where fr.vendor_id = x.min_id;
The equivalent to the LIMIT 1 approach in Oracle (just for reference) would be this:
select *
from
(
select *
from fruits frx
where frx.name > 'apples'
order by name
)
where rownum = 1
I don't know MySQL SQL but I still try
select n.id
from fruit n
, fruit p
where n.id = p.id + 1;
edit:
select n.id, n.fruitname
from fruits n
, fruits p
where n.id = p.id + 1;
edit two:
Jason Lepack has said that that doesn't work when there are gaps and that is true and I should read the question better.
I should have used analytics to sort the results on fruitname
select id
, fruitname
, lead(id) over (order by fruitname) id_next
, lead(fruitname) over (order by fruitname) fruitname_next
from fruits;
If you are using MS SQL Server 2008 (not sure if available for previous versions)...
In the event that you are trying to find the next record and you do not have a unique ID to reference in an applicable manner, try using ROW_NUMBER(). See this link
Depending on how savvy your T-SQL skill is, you can create row numbers based on your sorting order. Then you can find more than just the previous and next record. Utilize it in views or sub-queries to find another record relative to the current record's row number.
SELECT cur.id as id, nxt.id as nextId, prev.id as prevId FROM video as cur
LEFT JOIN video as nxt ON nxt.id > cur.id
LEFT JOIN video as prev ON prev.id < cur.id
WHERE cur.id = 12
ORDER BY prev.id DESC, nxt.id ASC
LIMIT 1
If you want the item with previous and next item this query lets you do just that.
This also allows You to have gaps in the data!
How about this:
Select * from table where id = 1 + 1