View Full Version : SQL Problem: Copying Fields
llbbl
08-31-2004, 07:32 AM
How do you copy a field in a table from one spot to another? Say you want to change the order what the fields appear in. MySQL running phpMyAdmin doesn't allow you to reorganize the order in which fields appear. I have thought of two ways I can solve this.
1) Using one big long convoluted SQL statement such as this.
SELECT `field1` FROM `Table` AND UPDATE `Table` SET `Table.field1` = `Table.field2` WHERE `Table.field1` =`Table.field1`
2) Write a Script to copy fields around.
3) Copy everything into a temporary table and using INNER JOIN's copy it over.
You cant, SELECT/high light, COPY, PASTE???
Stupid prog..
llbbl
08-31-2004, 11:03 AM
nope . that won't work . I treid MySQL control Center as well .. I haven't got the SQL statement correct yet .. might not be possible
llbbl
08-31-2004, 11:07 AM
Ok I found it
A.7.2 How to Change the Order of Columns in a Table
First, consider whether you really need to change the column order in a table. The whole point of SQL is to abstract the application from the data storage format. You should always specify the order in which you wish to retrieve your data. The first of the following statements returns columns in the order col_name1, col_name2, col_name3, whereas the second returns them in the order col_name1, col_name3, col_name2:
mysql> SELECT col_name1, col_name2, col_name3 FROM tbl_name;
mysql> SELECT col_name1, col_name3, col_name2 FROM tbl_name;
If you decide to change the order of table columns anyway, you can do so as follows:
1. Create a new table with the columns in the new order.
2. Execute this statement:
mysql> INSERT INTO new_table
-> SELECT columns-in-new-order FROM old_table;
3. Drop or rename old_table.
4. Rename the new table to the original name:
mysql> ALTER TABLE new_table RENAME old_table;
SELECT * is quite suitable for testing queries. However, in an application, you should never rely on using SELECT * and retrieving the columns based on their position. The order and position in which columns are returned will not remain the same if you add, move, or delete columns. A simple change to your table structure will cause your application to fail.
http://dev.mysql.com/doc/mysql/en/Change_column_order.html
I think that should work.
llbbl
08-31-2004, 11:11 AM
um, what's the actual need for this besides just a nice look in the
mysql client? you never should rely on the order of "select * from
table" anyway.
but, if there's a will, there's a way:
CREATE TABLE blaah (
col1 int,
col3 int,
col2 int
);
now, let's put them in order:
ALTER TABLE blaah ADD tempcol int AFTER col1;
UPDATE blaah SET tempcol=col2;
ALTER TABLE blaah DROP col2;
ALTER TABLE blaah CHANGE tempcol col2 int;
http://www.faqts.com/knowledge_base/view.phtml/aid/2711/fid/101
I want a nice looking client dangit!
vBulletin® v3.7.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.