I added an empty column to a table and now I want to insert sequential numbers to its rows. Is it possible to do it using SQL?
Run the following queries to have incremented value in yourField column:
SELECT #i:=0;
UPDATE yourTable SET yourField = #i:=#i+1;
As I said in comments you can update every row with its row number,
Here is a link to how to calculate rownum in MySQL.
To rephrase:
update player,
(select #rownum:=#rownum+1 ‘rank’, p.*
from player p,
(SELECT #rownum:=0) r
order by score desc) player1
set thatColumn= rank
where player.id = player1.id
try this auto increment
if you wanted to have incremental number in your table for each insert that you do
create table WithAutoInc(somID int AUTO_INCREMENT,somName_ char(100) ,primary key(somID ));
now to insert you can do this
insert into WithAutoInc (somName_) values ('presley');
the result is
Related
I've got the following table:
productId price
1 price_value1
2 price_value2
3 price_value3
I would like to insert a new product into the table and assign it a new productId. In this case its value equals to 4.
So I want my new table to look like so:
productId price
1 price_value1
2 price_value2
3 price_value3
4 price_value4
So as far as I understand, in order to do that I have to somehow retrieve the max value of productId and insert it using INSERT INTO mytable VALUES (productId + 1, price_value4).
But how do I find out the maximum value of productId?
I tried INSERT INTO mytable VALUES (SELECT MAX(productId) + 1 FROM mytable, price_value4) but it didn't work.
This should Work:
Select the max(productID) and price_value4 as a columns from mytable and insert the result.
INSERT INTO mytable (SELECT MAX(productId) + 1, 'price_value4' FROM mytable);
However, if you are not going to jump some number you can just add an auto increment id key to product_id and then you will have only to insert the price, the product ID will be incremented automatically..
This will do so :
ALTER TABLE mytable
MODIFY COLUMN `productId` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
you can change INT(10) with the INT(5) for example depanding on the size you want to give to your productId column
EDIT :
In return to the OP question in comments why his solution wouldn't work
Some suggetions says you have to make the SELECT statment in insert always between parenthesis
INSERT INTO mytable VALUES ( (SELECT MAX(ID)+1 FROM mytable) , price_value4)
.. In my Case it Return
(1093): You can't specify target table
'mytable' for update in FROM clause
AND HERE IS WHY (Quoting From the documentation)
When selecting from and inserting into the same table, MySQL creates
an internal temporary table to hold the rows from the SELECT and then
inserts those rows into the target table. However, you cannot use
INSERT INTO t ... SELECT ... FROM t when t is a TEMPORARY table,
because TEMPORARY tables cannot be referred to twice in the same
statement
BUT there is away to overcome by using a query instead of the table itself in the FROM, which has the effect of copying the requested table values instead of referencing the one that you are updating..
INSERT INTO mytable VALUES (
(SELECT MAX(ID)+1 FROM (SELECT * FROM mytable ) as mytmp ),
'price_value4');
OR (Quoting From the documentation)
To avoid ambiguous column reference problems when the SELECT and the
INSERT refer to the same table, provide a unique alias for each table
used in the SELECT part, and qualify column names in that part with
the appropriate alias.
INSERT INTO mytable Values ( (SELECT MAX(ID)+1 FROM mytable as mytmp) , 'price_value4')
This is a duplicate question. In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows.
A simple syntax to create table
CREATE TABLE Product (
productId MEDIUMINT NOT NULL AUTO_INCREMENT,
price INT NOT NULL,
PRIMARY KEY (productid)
);
While inserting supplied default or leave column as blank or supplied value as NULL. Take a look at below code snippet.
INSERT INTO Product (price) VALUES
('10'),('20'),('4'),
('30');
refer this link
How do i update current row value if my previous row are same with current row.
example:
the curent row is 68, previous row is also 68.. i would i like to update current row become 68-20 which is 48.
same for 98-20 = 78.
so that the corrected data will look like:
i have more than 1000 record like this, which cant update the record one by one manually.
update table1 set DIH_QTY_BALANCE=DIH_QTY_BALANCE-DIH_REORDER_QTY
WHERE how to put the previous row same as current on where clause?
Here is the Schema + data:
http://pastebin.com/T1tYDT6Y
too large for sqlfiddle.
any help would be great.
As far as I remember, MySQL has problems to select from the same table in an update statement. And this is what you would have to do, because in order to update a record or not, you'd have to select its previous record from the same table.
So create a temporary table, give it row numbers, then select from it with a self join, to compare each record with its previous record.
create temporary table temp
(
rownum int,
dihistoryid int,
dih_qty_balance int
) engine = memory;
set #num = 0;
insert into temp
select
#num := #num + 1 as rownum,
dihistoryid,
dih_qty_balance
from mytable
order by dihistoryid;
update mytable
set dih_qty_balance = dih_qty_balance - dih_reorder_qty
where dihistoryid in
(
select current.dihistoryid
from temp current
join temp previous on previous.rownum = current.rownum - 1
where previous.dih_qty_balance = current.dih_qty_balance
);
drop temporary table temp;
May be something like this
SELECT DIH_QTY_BALANCE,
(SELECT DIH_QTY_BALANCE FROM example e2
WHERE e2.DIHISTORYID < e1.DIHISTORYID
ORDER BY DIHISTORYID DESC LIMIT 1) as previous_value,
(SELECT value FROM example e3
WHERE e3.DIHISTORYID > e1.DIHISTORYID
ORDER BY DIHISTORYID ASC LIMIT 1) as next_value
FROM example e1
Hoping someone can help me with a mysql query
Here’s what I have:
I table with a column “networkname” that contains data like this:
“VLAN-338-Network1-A,VLAN-364-Network2-A,VLAN-988-Network3-A,VLAN-1051-Network4-A”
I need a MySQL query that will update that column with only the vlan numbers in ascending order, stripping out everything else. ie.
“338, 364, 988, 1051”
Thanks,
David
In this script, I create a procedure to loop through the networkname values and parse out the numbers to a separate table, and then update YourTable using a group_concat function. This assumes your networkname values follow the 'VLAN-XXX' pattern in your example where 'XXX' is the 3-4 digit number you want to extract. This also assumes each record has a unique ID.
CREATE PROCEDURE networkname_parser()
BEGIN
-- load test data
drop table if exists YourTable;
create table YourTable
(
ID int not null auto_increment,
networkname nvarchar(100),
primary key (ID)
);
insert into YourTable(networkname) values
('VLAN-338-Network1-A,VLAN-364-Network2-A,VLAN-988-Network3-A,VLAN-1051-Network4-A'),
('VLAN-231-Network1-A,VLAN-4567-Network2-A'),
('VLAN-9876-Network1-A,VLAN-321-Network2-A,VLAN-1678-Network3-A');
-- add commas to the end of networkname for parsing
update YourTable set networkname = concat(networkname,',');
-- parse networkname into related table
drop table if exists ParseYourString;
create table ParseYourString(ID int,NetworkNumbers int);
while (select count(*) from YourTable where networkname like 'VLAN-%') > 0
do
insert into ParseYourString
select ID,replace(substr(networkname,6,4),'-','')
from YourTable
where networkname like 'VLAN-%';
update YourTable
set networkname = right(networkname,char_length(networkname)-instr(networkname,','))
where networkname like 'VLAN-%';
end while;
-- update YourTable.networkname with NetworkNumbers
update YourTable t
inner join (select ID,group_concat(networknumbers order by networknumbers asc) as networknumbers
from ParseYourString
group by ID) n
on n.ID = t.ID
set t.networkname = n.networknumbers;
END//
Call to procedure and select the results:
call networkname_parser();
select * from YourTable;
SQL Fiddle: http://www.sqlfiddle.com/#!2/01c77/1
I want to do an insert into my database like this. But the Table's may have 200k+ records in them. I want to split up the inserts into groups of 10,000 or so, how can I do this efficiently in MySQL only?
INSERT INTO `slugs` (`sku`, `tablename`)
select `SKU`, 'tableA'
from `tableA`
WHERE `SKU` NOT IN
(select `sku` from `slugs` where `tablename` = 'tableA');
Example Code: http://sqlfiddle.com/#!2/a75a1/8
Add a LIMIT 10000 to the end and run it until rows inserted = 0.
If it is not a one shot, you can do this in a procedure with a loop..
Try this:
SET #rank=0;
select rank
, IF(MOD(rank,10000)=0,CONCAT(IF(MOD(rank,10000)=1,CONCAT("insert ignore into table values (""",NAME,""",""",SKU,""")"),CONCAT(",(""",NAME,""",""",SKU,""")")),";"),IF(MOD(rank,10000)=1,CONCAT("insert ignore into table values (""",NAME,""",""",SKU,""")"),CONCAT(",(""",NAME,""",""",SKU,""")"))) as insert_statement
from (
SELECT #rank:=#rank+1 AS rank,NAME,SKU
from tablea
) der
I have a database. I want to update a column of it. The column should contain unique integer numbers in ascending order according to alphabetical order of another column.
Sorry not clear maybe, I want to have integer numbers like this:
1 ACC 501
2 BCC 501
3 GCC 601
4 FCC 601
Is there a reasonably simple way of setting this rank/order with mysql or sql query?
What you need is a ranking function which is not supported by MySQL at the moment. However, you can simulate them like so:
Set #rownum := 0;
Select rnk, SomeCode, SomeNum
From (
Select #rownum := #rownum + 1 As rnk, SomeCode, SomeNum
From MyTable
Order By SomeCode Asc
) As Z
Create another table that has the same schema as your original table, plus the new column. The new column should be an autonumber. Do an INSERT...SELECT into that table. The new column will be filled out with the values you want.
Like what Alex said, you want to create a new table like
CREATE TABLE newTable(
#Table definition from current table,
id INT NOT NULL AUTO_INCREMENT
);
And then insert with
INSERT INTO newTable
SELECT * FROM oldTable
ORDER BY orderColumn;
I think you can quickly do the create table with
CREATE TABLE newTable LIKE oldTable;
ALTER TABLE newTable ADD COLUMN id INT NOT NULL AUTO_INCREMENT;