Mysql database change ordering of records - mysql

Here I have data in mysql database that is reversed in order. How to change the ordering so that default ordering that is ASC is reversed.
Primary field is ID. ANd ID is auto_increment. I need to change the ID fields in reverse order for each records.
For example. Let's assume I have 2 records in table.
ID field
1 field1
2 field2
I want to have field2 to have ID 1 and field1 to have ID 2

You could do:
ALTER TABLE `table` ORDER BY `ID` DESC
but its bad database design
its against First normal form

or you can export the entire table in script file. "sql" and once the script in hand you can put in order all the (INSERT INTO) backwards. It takes a few minutes but it works
1: generate script from your base..you can use phpmyadmin or console line mysql
2. reverse the insert command
Base script Before:
INSERT INTO example (name, age) VALUES('Sandy Smith', '21' )
INSERT INTO example (name, age) VALUES('peter brad', '38' )
INSERT INTO example (name, age) VALUES('mike alves', '24' )
base script After:
INSERT INTO example (name, age) VALUES('mike alves', '24' )
INSERT INTO example (name, age) VALUES('peter brad', '38' )
INSERT INTO example (name, age) VALUES('Sandy Smith', '21' )
it is a slower but can it clean
OHTER solution ->
You can then try something like this: - Create a new table with the information from the original table by retrieving all the id and reversing with ORDER BY!
CREATE TABLE newtable SELECT ID, row1, row2, row3, row4, row5 FROM oldtable ORDER BY id DESC ;
And then delete the old table It should work without problem

Related

Insert type id in table

How to insert score with value and score_id ? At server im know only score_type.name and score.value. How i can insert new score with score_type ? If score_type name exsist just get id and insert, else create, get id and insert.
First try to create the score_type if it doesn't exist:
INSERT IGNORE INTO score_type (name) VALUES ("type_name");
Then use INSERT ... SELECT to insert the ID into the score table:
INSERT INTO score (value, score_type_id, player_id)
SELECT 123, id, "player_name"
FROM score_type
WHERE name = "type_name";
The first INSERT assumes you have a unique index on score_type.name. IGNORE means to fail silently if you try to insert a duplicate name.
Replace 123 and player_name with the known score.value and score.player_id.
If I understood your question correctly, you want to fill the score_type_id dynamically by selecting it using the name:
INSERT INTO `score`(`value`, `score_type_id`, `player_id`) VALUES (1337, (SELECT id FROM score_type WHERE score_type.name = "test") ,"maio290");
The trick is just to use another query instead of a fixed value.

Insert row if there isn't already a row with the same id and url (two column values)

I would like to write a SQL statement that inserts a new row into the database if there isn't already a row for it. The unique identifier of a row is the id and url. Let's say the table schema looks like this:
LinkClicks: (id, url, clicks)
So now let's say I've got a row with a parameterized SQL insert. I'm attempting to do something like this:
INSERT (id, url, clicks)
INTO LinkClicks Values(#id, #url, #clicks)
WHERE #url NOT IN
(SELECT url FROM LinkClicks WHERE id=#id);
I think you want something like this:
INSERT INTO LinkClicks(id, url, clicks)
SELECT id, url, clicks
FROM (SELECT #id as id, #url as url, #clicks as clicks) t
WHERE t.url NOT IN (SELECT url FROM LinkClicks WHERE id = #id);
You can add a unique index on the id and url columns:
ALTER TABLE LinkClicks ADD UNIQUE u_idx (id, url);
With this constraint in place, attempts to insert a record whose id and url combination of values already appears will fail at the database level.
This might be preferable to the query you are attempting, because it guarantees that MySQL will reject a duplicate attempt to insert. A query could also be used to this effect, but later on perhaps someone else using your code base might forget this.
In fact you should take Tim's advice and put the unique index on the table but in doing so you need a fail safe way of ensuring that you don't attempt to put duplicates (id and url) into the table (otherwise loads of red-ink messages). This way seems ok:
DROP TABLE LINKCLICKS
DROP TABLE LINKCLICKS1
CREATE TABLE LINKCLICKS
(
[ID] INT,
[URL] CHAR(11),
CLICKS BIGINT
)
GO
INSERT INTO LINKCLICKS VALUES (1001,'www.abc.com',40000)
INSERT INTO LINKCLICKS VALUES (1002,'www.def.com',40000)
INSERT INTO LINKCLICKS VALUES (1003,'www.ghi.com',40000)
GO
CREATE TABLE LINKCLICKS1
(
[ID] INT,
[URL] CHAR(11),
CLICKS BIGINT
)
GO
INSERT INTO LINKCLICKS1 VALUES (1001,'www.abc.com',40000)
INSERT INTO LINKCLICKS1 VALUES (1003,'www.def.com',40000)
INSERT INTO LINKCLICKS1 VALUES (1004,'www.ghi.com',40000)
GO
WITH CTE1 AS
(
SELECT *,'d' AS [Source] FROM LINKCLICKS
UNION ALL
SELECT *,'s' AS [Source] FROM LINKCLICKS1
)
,
CTE2 AS
(
SELECT ID,[URL] FROM CTE1 GROUP BY ID,[URL] HAVING COUNT(ID) =1 AND COUNT([URL]) =1
)
INSERT INTO LINKCLICKS
SELECT ID,[URL],CLICKS
FROM CTE1
WHERE [Source] <> 'd'
AND
(
ID IN (SELECT ID FROM CTE2) AND [URL] IN (SELECT [URL] FROM CTE2)
)
SELECT * FROM LINKCLICKS ORDER BY [ID],URL
GO
The INSERT statement only inserts those rows where the ID and URL combined are not the same as rows already in the destination table. It quite happily inserts rows where either the IDs are the same but the URLs are different or where the IDs are different but the URLs are the same.
My only reservation is the question of 'dupes' in the source table (in this case LINKCLICKS1). If there are duplicates in the source table, none of them will be inserted into the destination table. This will defeat the object of the query.
The answer is, if you have duplicates, or any risk of duplication in the source table, then you should apply 'de-dupe code' to the source table before you run this.
If you need any de-dupe code, put a comment below.

mysql insert record without using 'values'

INSERT INTO class
(name, description, personid)
Select name, description, 12 from Class where PersonID = 3;
Select * from Class
Select * from Person
Why is the values words is missing from above statement? I thought it should be like this insert into tableA('name') values('select name from tableB') ?
INSERT INTO my_table VALUES ()
Insert data one Table to another table
OR
Not Using Value keyword
Insert into Table2 (Name , Address , Mobile) Select Column 1, Column 2 , Column 3 From Table1
There are different techniques of INSERT, the code above is inserting values from the table itself and change only the personid to 12, he use select so that he can copy the data aside from hardcoded personid . that's why you didn't see the VALUES keyword , but that's true.. the basic insert statement we learn from school is INSERT INTO TableName (Col1, Col2... etc) VALUES (Value1, Value2... etc) , INSERTION of data depends on the requirements that you are working on.

Cannot insert row when table is empty in MySql

I wanna insert a row when the name not exists in the table.
When the table is empty,it cannot insert anything, anyone can help me?
Here is my code:
INSERT INTO `ediftpdb`.`users`(
name
,passwd
,vendor
)
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM `ediftpdb`.`users`
WHERE NOT EXISTS (SELECT * FROM `ediftpdb`.`users` WHERE name='L001' AND vendor = 'MKTPLS' ) LIMIT 1;
P.S.
I found a funny stuff, when ediftpdb.users is empty, code like below returns nothing.
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM `ediftpdb`.`users`
The better way to do this is to create a unique multi-part index on name and vendor columns:
CREATE UNIQUE INDEX name_vendor ON ediftpdb.users( name, vendor )
Then:
INSERT IGNORE INTO ediftpdb.users ( name, passwd, vendor )
VALUES ( 'L001', '12345678a', 'MKTPLS' )
will do exactly what you want to do.
As #Martin Smith pointed, when the table ediftpdb.users is empty the FROM ediftpdb.users
results in no rows. If it had 100 rows, then your statement would try to INSERT 100 (identical) records into the table.
Try this:
INSERT INTO
...
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM (SELECT 1) AS dummy
WHERE NOT EXISTS ...

MySql Query - INSERT INTO command but only without duplicates

I have this workable query which is inserting proper data into 'selections' table according to some conditions:
INSERT INTO selections (auctionid, selections.order)
VALUES
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 1,
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 2,
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 3
but my problem is how to improve this query to prevent getting same duplicates in table when running this query?
Selections table have 3 columns: id, auctionid, order where id is autoincrement number generated for each new record.
So auctionid and order shouldn't be the same values in record.
Add a UNIQUE INDEX to the (auctionid, order) pair.
ALTER TABLE selections ADD UNIQUE index_name (`auctionid`, `order`)
And when you insert you can use INSERT IGNORE INTO ... so that it ignores duplicates instead of throwing an error. (Useful when you batch insert and the duplicates are expected)
SOLVED!
Created 3 separated queries for each row, working for now!
So with added UNIQUE INDEX to the (auctionid, order) pair have this workable code:
INSERT IGNORE INTO
selections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
1,
PlayerA,
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;
INSERT IGNORE INTO
elections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
2,
PlayerB,
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;
INSERT IGNORE INTO
selections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
3,
'third text',
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;