[英]mysql insert + select row_id
Suppose I have two table: 假设我有两张桌子:
create table ladder (
user_id INT UNSIGNED NOT NULL PRIMARY KEY
, rank INT UNSIGNED NOT NULL UNIQUE
);
create table myuser (
user_id INT UNSIGNED NOT NULL PRIMARY KEY
, rating INT UNSIGNED NOT NULL
);
myuser consists of a rating, where higher rating represent a better user. myuser由评级组成,其中较高的评级代表更好的用户。 ladder is the ranking table, rank is range from 1, 2,3, 4, 5... where the user_id with rank=1 has the highest rating. 梯级是排名表,排名范围从1,2,3,4,5 ...其中具有rank = 1的user_id具有最高评级。
ok, when i do an INSERT + SELECT : 好吧,当我做INSERT + SELECT时:
DELETE FROM ladder; -- clean the table first
INSERT INTO ladder (user_id, rank) SELECT user_id, XXX FROM myuser ORDER BY rating;
then I need something like XXX represent the ROW id of the SELECT myuser, so that XXX = 1 for the first row, 2 for the second row. 然后我需要像XXX这样代表SELECT myuser的ROW id,这样第一行的XXX = 1,第二行的XXX。
is this possible ? 这可能吗 ?
(or XXX = 0 for the first row, and i will do XXX+1 in select)
There is no such ROW_NUM
in MySQL
. MySQL
没有这样的ROW_NUM
。 Generate it while running the SELECT
statement and use. 在运行SELECT
语句时生成它并使用。
Example : 示例 :
INSERT INTO ladder (user_id, rank)
SELECT
user_id, @r:=(@r + 1 )
FROM
myuser,
( SELECT @r:=0 )
ORDER BY rating;
Demo : Example @ SQL Fiddle 演示 : 示例@ SQL小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.