Double the records in the database using MySQL - php

How do I double or triple the rows (duplication also fine) in an existing table using mysql?

This should do the trick, if you have no PRIMARY KEY or UNIQUE indexes.
INSERT INTO table SELECT * FROM table;
If you do have such indexes, simply list all the columns in the table that do not have these indexes. E.g. if colA has a UNIQUE or PRIMARY KEY index:
INSERT INTO table (colB, colC) SELECT colB, colC FROM table;
Note that this will only work if your ID column (colA) has the AUTO_INCREMENT property set (this is usually the case for integer ID columns). If not then you are out of luck. In that case you cannot use INSERT INTO ... SELECT to duplicate rows because you need to supply the unique indexes manually.

In words,
use select to get everything, than use insert....

You shouldn't do that.
Keep your tables in Normal form that means no duplicates.

INSERT INTO table (SELECT * FROM table)
You have to exclude the primary key.
INSERT INTO table (col1, col2) SELECT col1, col2 FROM table;
Do not select primary key.
You have to mention all the fields excluding primary key. I believe you have an auto-increment column do not mention that column in above command but include all other columns.

I agree with Col. Shrapnel: you should not do this.
Sander got it right:
if you want to do this, INSERT INTO
table SELECT * FROM table is the way
to go
If there is a PRIMARY AUTOINCREMENT key, insert into table (all-but-key) select all-but-key from table
If there are other UNIQUE keys, you can't do this.
Another dirty workaround:
SELECT * FROM TABLE UNION ALL SELECT * FROM TABLE
You could put this in a VIEW or a merge table...

An easy way to duplicate all rows in the same table:
INSERT INTO yourtable()
SELECT * FROM yourtable;
This ofc only works if you don't have any unique keys on the table.

Related

How would I go about automatically shifting the auto-increment id element in my sql table after I delete an element? [duplicate]

How would I reset the primary key counter on a sql table and update each row with a new primary key?
I would add another column to the table first, populate that with the new PK.
Then I'd use update statements to update the new fk fields in all related tables.
Then you can drop the old PK and old fk fields.
EDIT: Yes, as Ian says you will have to drop and then recreate all foreign key constraints.
Not sure which DBMS you're using but if it happens to be SQL Server:
SET IDENTITY_INSERT [MyTable] ON
allows you to update/insert the primary key column. Then when you are done updating the keys (you could use a CURSOR for this if the logic is complicated)
SET IDENTITY_INSERT [MyTable] OFF
Hope that helps!
This may or not be MS SQL specific, but:
TRUNCATE TABLE resets the identity counter, so one way to do this quick and dirty would be to
1) Do a Backup
2) Copy table contents to temp table:
3) Copy temp table contents back to table (which has the identity column):
SELECT Field1, Field2 INTO #MyTable FROM MyTable
TRUNCATE TABLE MyTable
INSERT INTO MyTable
(Field1, Field2)
SELECT Field1, Field2 FROM #MyTable
SELECT * FROM MyTable
-----------------------------------
ID Field1 Field2
1 Value1 Value2
Why would you even bother? The whole point of counter-based "identity" primary keys is that the numbers are arbitrary and meaningless.
you could do it in the following steps:
create copy of yourTable with extra column new_key
populate copyOfYourTable with the affected rows from yourTable along with desired values of new_key
temporarily disable constraints
update all related tables to point to the value of new_key instead of the old_key
delete affected rows from yourTable
SET IDENTITY_INSERT [yourTable] ON
insert affected rows again with the new proper value of the key (from copy table)
SET IDENTITY_INSERT [yourTable] OFF
reseed identity
re-enable constraints
delete the copyOfYourtable
But as others said all that work is not needed.
I tend to look at the identity type primary keys as if they were equivalent of pointers in C, I use them to reference other objects but never modify of access them explicitly
If this is Microsoft's SQL Server, one thing you could do is use the [dbcc checkident](http://msdn.microsoft.com/en-us/library/ms176057(SQL.90).aspx)
Assume you have a single table that you want to move around data within along with renumbering the primary keys. For the example, the name of the table is ErrorCode. It has two fields, ErrorCodeID (which is the primary key) and a Description.
Example Code Using dbcc checkident
-- Reset the primary key counter
dbcc checkident(ErrorCode, reseed, 7000)
-- Move all rows greater than 8000 to the 7000 range
insert into ErrorCode
select Description from ErrorCode where ErrorCodeID >= 8000
-- Delete the old rows
delete ErrorCode where ErrorCodeID >= 8000
-- Reset the primary key counter
dbcc checkident(ErrorCode, reseed, 8000)
With this example, you'll effectively be moving all rows to a different primary key and then resetting so the next insert takes on an 8000 ID.
Hope this helps a bit!

Mysql duplicate row prevention [duplicate]

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

how to find the missing values in a mysql table from an array

i hava a table with varchar primary key, that is a foreing key for some other tables.
Something like:
ID-------------NAME
1011001020-----product 1
1011001022-----product 2
1011001025-----product 3
Then, i have this array
array(
'1011001020',
'1011001022',
'1011001025',
'x',
'y'
)
This array will be used to insert values in another table with FK, so if any value is not an ID on the first table, the INSERT query will brake.
How do i find 'x' and 'y' before any attempt to insert. I would like to avoid selecting all ids from table one and make a PHP comparison, since there are a lot of records. I would rather a MySQL approach
I would suggest the following procedure:
Create the table and insert all the values into the table.
Remove the values that do not match.
Add the foreign key constraint.
The second and third steps can be done easily in SQL:
delete from temporarytable
where tt.otherid not in (select ot.otherid from othertable ot);
alter table temporarytable
add constraint fk_othertable foreign key (otherid) references othertable(otherid);
You can load the data however you like. For speed, I would recommend load data infile.
give this a shot. Tested on server, products is the new table and inserted only rows found in the array from items table.
INSERT INTO `products` ( `name` )
SELECT `name` FROM `items` WHERE `vendor_id` IN ( 1,2,3,4,.... )

copy several mysql rows based on foreign key

I want to copy several rows in a mysql table based on a foreign key, and asign the new rows a new foreign key ID. Assuming my table layout looks like this:
test
-----
table1_id int(11)
value varchar(20)
How do I accomplish this?
Found out that the query would need to look like this:
INSERT INTO test (table1_id, value) (SELECT '2', value FROM test WHERE table1_id=1)
which would copy all rows with the foreign key ID '1' and assign the new rows with ID 2 instead. If the table contains more rows you could add them or change order in the SELECT part, like this
...(SELECT row1, '{$new_id}', value, another_row FROM...

Select Primary Key Value Without Knowing Field Name

I have 3 tables, images, icons, and banners, each with a unique primary key that is also auto_incremented named image_id, icon_id, and banner_id, respectively.
I'm looping through the above tables and I'm wondering if there's a way I can select the id column without specifying it's specific name.
Something like
SELECT PRIMARY_KEY
FROM {$table}
Where I don't have to change my table structure or use * as there would be much data to return and would slow down my application.
Just name the id columns id in each table. Reserve the whatever_id naming for foreign keys.
I'm not a LAMP guy, but it looks to me like you want the INFORMATION_SCHEMA tables.
A query something like :
SELECT pk.table_name, column_name as 'primary_key'
FROM information_schema.table_constraints pk
INNER JOIN information_schema.key_column_usage C
on c.table_name = pk.table_name and
c.constraint_name = pk.constraint_name
where constraint_type = 'primary key'
-- and pk.table_name LIKE '%whatever%'
This above query (filtered to whatever relevant set of tables you need) will give you bit a list of table names and associated Primary Keys. What that information on hand you could query something like :
SELECT {$PK_ColumnName}
FROM {$table}
Note, you might needs a more complicated syntax and string builder if you have composite primary keys (i.e. more than one field per key). Also, the information schema can be relatively expensive to query, so you'll either want to cache the result set up, or query it infrequently.
The PRIMARY key is different than the column that has the primary key on it. The primary key is both an index and a constraint that is placed on one or more columns, not a column itself. Your pseudocode query:
SELECT PRIMARY_KEY
FROM tablename
is equivalent to this:
SELECT keyname
FROM tablename
Which is invalid. What you really need to select is a column, not a key.
Unfortunately, there is no column alias or simple function that you can use to specify the columns that have the primary key constraint. It's most likely not available because the primary key can apply to more than one column.
To see which columns have the PRIMARY key constraint, you could use some reflection by querying the schema tables, using SHOW COLUMNS, etc.. Simply doing SELECT * FROM tablename LIMIT 1 would get you all the column names in the result, if you wanted to assume the first column had the primary key constraint.
Of course, you could just do SELECT * anyway, when you don't know the column name.
If you don't want to make an extra query to fetch the column name to construct the query, using built-in meta data, or your own, I'd heed Marc B's answer if you can.
Or you can use the standard SQL command
show columns from tablename
It will show the PRI column
Check the online documentation for more info

Categories