Duplicate a row with data changing - mysql

I have a mysql table with several columns. on some conditions I run a script that duplicates the row.
This is done via these steps:
select all columns from the row to be duplicated
on the resulting array change two values out of 30 (new info are built on the fly using php scripts and are unique for the row). these values can be created any time during the update process
insert the new row with the usual insert into... that make me list again all the 30 fields and values
My question is: is there a way to change this script into:
create the new values
run a single query that will duplicate the row and at the same time update the values while duplicating?
So that i don't need to manipulate the array in php and I run just one query instead of two?

You can do it with a single query, but you will need to list all the fields:
INSERT INTO your_table
SELECT
NULL, #in place of auto-increment column (if any)
'some value for the field you want to change',
'some value for another field you want to change',
not_changed_field1,
not_changed_field2,
...
FROM your_table
WHERE <row has to be duplicated>

Related

Mysql insert multiple rows if each not between 2 column range?

Using PHP I dynamically generate multiple values and insert them into a table, simplified example of an insert with some values:
INSERT INTO table (time1,time2)
VALUES ('08:00','09:00'),('09:00','10:00'),('11:00','12:00');
With the above example, I'd like to prevent this from inserting:
INSERT INTO table (time1,time2)
VALUES ('08:15','08:45'),('09:30','12:00');
Is it possible to make a range comparison between 2 columns when inserting multiple values? Or would I need to make a loop with single inserts (which I'd like to avoid for performance reasons)?
EDIT: I'm submitting the data by form with PHP. I guess the logical step is to use $_POST values and do a SELECT checking if the times conflict. Whether to use BETWEEN in SELECT or return all values back for a PHP function is another matter.
Check for indivisual entries form php, use this query to check the number of conflicts the new entry is making:
SELECT count(*) as `conflicts`
FROM table
WHERE
'08:15' BETWEEN time1 AND time2 -- user your variable here
OR
'08:45' BETWEEN time1 AND time2 -- user your variable here

How to update a value while inserting rows from one table into another?

I'm trying to insert rows into a table while ignoring duplicate entries. At the same time, I want to assign a value to a certain column in the newly inserted rows.
Here's what I have so far (without assigning the value)
INSERT INTO stats (unique_key,clicks)
SELECT unique_key,clickss FROM temp_stats
ON DUPLICATE KEY UPDATE stats.unique_key=temp_stats.unique_key;
I would like to throw in clicks = 20 for the newly inserted rows.
How would I achieve this?
Just select the literal value, instead of the field from the table.
INSERT INTO stats (unique_key,clicks)
SELECT unique_key,20 FROM temp_stats
ON DUPLICATE KEY UPDATE stats.unique_key=temp_stats.unique_key;

REPLACE versus INSERT in SQL

I am doing the following SQL tutorial: http://sql.learncodethehardway.org/book/ex11.html
and in this exercise the author says in the second paragraph:
In this situation, I want to replace my record with another guy but
keep the unique id. Problem is I'd have to either do a DELETE/INSERT
in a transaction to make it atomic, or I'd need to do a full UPDATE.
Could anyone explain to me what the problem is with doing an UPDATE, and when we might choose REPLACE instead of UPDATE?
The UPDATE code:
UPDATE person SET first_name = "Frank", last_name = "Smith", age = 100
WHERE id = 0;
Here is the REPLACE code:
REPLACE INTO person (id, first_name, last_name, age)
VALUES (0, 'Frank', 'Smith', 100);
EDIT: I guess another question I have is why would you ever do a DELETE/INSERT instead of just an UPDATE as is discussed in the quoted section?
According to the documentation, the difference is:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
So what it does:
Try to match the row using one of the available indexes;
If the row doesn't exist already: add a new one;
If the row exists already: delete the existing row and add a new one afterwards.
When might using this become useful over separate insert and update statements?
You can safely call this, and you don't have to worry about existing rows (one statement vs. two);
If you want related data to be removed when inserting / updating, you can use replace: it deletes all related data too);
When triggers need to fire, and you expect an insert (bad reason, okay).
First Replace isn't widely understood in all database engines.
Second replace inserts/updates a record based on the primary key. While with update you can specify more elaborate conditions:
UPDATE person SET first_name = 'old ' + first_name WHERE age > 50
Also UPDATE won't create records.
UPDATE will have no effect if the row does not exist.
Where as the INSERT or REPLACE will insert if the row doesn't exists or replace the values if it does.
Update will change the existing records value in table based on particular condition. So you can change one or many records in single query.
Insert or Replace will insert a new record if records is not present in table else will replace. Replace will only work if and only if you provide the primary key value in the insert or replace query. If you forget to add primary key field value than a new record will created in table.
Case example:-
Update: You have a calculation of wages to be done based on a formula using the column values. In this case you will always use update query as using one single query you can update multiple records.
Insert or Replace: Already mentioned in the link you shared.
How the REPLACE INTO statement works:
AS INSERT:
REPLACE INTO table_name (column1name, column2name, ...)
VALUES (value1, value2, ...);
AS UPDATE:
REPLACE INTO table_name SET column1name = value, column2name = value, ... ;
The REPLACE statement checks whether the intended data record's unique key value already exists in the table before inserting it as a new record or updating it.
The REPLACE INTO statement attempts to insert a new record or modify an existing record. In both cases, it checks whether the unique key of the proposed record already exists in the table. Suppose a value of NO or FALSE is returne. In that case, the REPLACE statement inserts the record similar to the INSERT INTO statement.
Suppose the key value already exists in the table (in other words, a duplicate key). In that case, the REPLACE statement deletes the existing record of data and replaces it with a new record of data. This happens regardless of whether you use the first or the second REPLACE statement syntax.
Once the REPLACE INTO statement is used to insert or modify data, it determines first whether the new data record already exists in the table. It checks if the PRIMARY or the UNIQUE KEY matches one of the existing records.
If there is no matching key, the REPLACE works like a normal INSERT statement. Otherwise, it deletes the existing record and replaces it with the new one. This is considered a sort of modification or update of an existing record. However, it would be best if you were careful here. Suppose you do not specify a value for a column in the SET clause. In that case, the REPLACE statement uses the default value (if a default value has been set). Otherwise, it's set as NULL.

MySQL Column wise Insert

I am trying to create a calculation logic using MySQL tables.
Data from two table is processed using a stored procedure and a set of values is generated.
These values are part of a column of output table.
I have to run different procedure to generate output for each column in output table
Now if I create insert query for each row it will have large number of inserts for each column. Can I insert a set of values into a table column in one go? assuming other columns can be NULL.
INSERT INTO tableName(columnName)
VALUES ('baz'),('foo'),('bar'),('baz'),('baz'),('baz'),('baz');
etc as u like..
See this: Bulk insert into table with one single query
The insert can be done for one column rest can be NULL if remaining columns are nullable.
But next time for the remaining columns the Insert will not work for the existing rows. If You want to update the existing rows then you need to fire the update query.
Assuming col1 and col2 are nullable
If you want to insert in col1 keeping col2 null insert will work
If you want to insert in col2 keeping col1 null insert will work

modify table with column with null values

what if I wanted to update the records in the table by altering values in one of the columns?
I have records in the table that have one column empty(null values). I want to change these values and insert values from another table into those records.
Basically I have a table with one column empty. I do not want to append to the end of the table but start inserting from record 1.
For the existing records, you would have to use UPDATE to update that one column, WHERE thatColumn IS NULL.
Shouldn't the values in that column have some relation to the rest of the record? I could understand initializing the existing records to a non-null value, or using an UPDATE query to populate data from another table in that column, but all related to the original row...
UPDATE old SET old.badColumn = new.newData
FROM oldTable old
JOIN newTable new on old.someID = new.someID
This would find the related data in newTable matching oldTable, and update the badColumn to some data from newTable... let me know if you need more help.
See the "Using the UPDATE statement with information from another table" section from this page of SQL Server Books Online.