简体   繁体   中英

Inserting sorted values from one MySQL table into another table

I have two tables, average_table and position_table . They have two column each. I would like to copy sorted data from average_table into position_table as shown below

The average_table looks like this

std_id       avr
001          23.4
002          34.7
003          13.9
004          56.8

then the position_table should look like this:

std_id      avr
004         56.8
002         34.7
001         23.4
003         13.9

When I used the following sql queries, the result was no different between average_table and position_table . Can some one help me out please?

try {
    String str = "insert into POSITION_TABLE select * from AVERAGE_TABLE ORDER BY avr DESC";
  rs = st.executeQuery(str);
}
catch(SQLException ce){System.out.print(ce)}

In the SQL world rows aren't really sorted. There might be a way to do this in MySQL (in SQL server, I think a clustered might do it - but for another reason than getting the rows in order).

In other words, an inserted row is not guaranteed to have a specific order. As SQL is declarative, you have to declare how to order it when you query.

I don't understand what you're trying to achieve with the position table - to me it looks like an exact duplicate of the average table and you're getting the data in ranked order already with your query using the order by. Just use order by when you need the data ordered.

create table average_table
(   std_id int not null,
    avr decimal(8,2) not null
);
insert average_table (std_id,avr) values (1,23.4),(2,34.7),(3,13.9),(4,56.8);

create table position_table
(   id int auto_increment primary key,
    std_id int not null,
    avr decimal(8,2) not null
);

insert into position_table(std_id,avr) select std_id,avr from average_table order by avr desc;

select * from position_table;
+----+--------+-------+
| id | std_id | avr   |
+----+--------+-------+
|  1 |      4 | 56.80 |
|  2 |      2 | 34.70 |
|  3 |      1 | 23.40 |
|  4 |      3 | 13.90 |
+----+--------+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM