这应该是一个非常简单的问题,但我无法弄清楚。在mysql表中,两列是questionNumber
和rowNumber
。我想按rowNumber
更新questionNumber
订单。这是我的PHP,问题在于查询("UPDATE Question SET rowNumber = ($x=$x+1) ORDER BY QuestionNumber")
。任何帮助我的帮手?
<?php
$link = mysqli_connect($dbhost, $username, $dbpass, $database);
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$x = 0;
$sql = "UPDATE Question SET rowNumber = ($x=$x+1) ORDER BY QuestionNumber";
if ($link->query($sql) === TRUE) {
echo "Updated";
} else {
echo "Error updating record: " . $link->error;
}
$link->close();
?>
答案 0 :(得分:1)
也许您可以在没有$x
的情况下执行此操作,请尝试以下操作:
UPDATE t1 Question t1
INNER JOIN (
SELECT @rowno := @rowno + 1 AS rowno, QuestionNumber
FROM Question
CROSS JOIN (SELECT @rowno := 0) t
ORDER BY QuestionNumber
) t2
ON t1.QuestionNumber = t2.QuestionNumber
SET t1.rowNumber = t2.rowno
答案 1 :(得分:1)
这是我刚刚放在一起的视觉效果。想象一下有一个城市和州的桌子,以及一个rownum专栏!
我想更新rownum列,但仅针对state = South Carolina ... SC
的行我希望更新顺序是城市名称。并且最初以物理顺序插入数据,以通过使SC城市名称最初未按字母顺序插入来显示其工作。
<强>架构:强>
drop table if exists locat123;
create table locat123
( id int auto_increment primary key,
city varchar(100) not null,
state varchar(100) not null,
rownum int not null
);
insert locat123 (city,state,rownum) values
('a1','NY',-1),('a2','NY',-1),('a3','NY',-1),('a4','NY',-1),
('m1','MT',-1),('m2','MT',-1),
('s8','SC',-1),('s2','SC',-1),('s4','SC',-1),('s1','SC',-1),('s11','SC',-1);
包含派生表的Update语句:
update locat123 l
join
( select l.id,l.city,@rn:=@rn+1 as rown
from locat123 l
cross join (select @rn:=0) params
where l.state='SC' -- <==================== right there, update SC only
order by l.city -- By the way, 5 rows that are South Carolina (SC) in here
) xDerived
on l.id=xDerived.id
set l.rownum=xDerived.rown;
-- 5 rows updated
<强>结果:强>
select * from locat123 order by state,city;
+----+------+-------+--------+
| id | city | state | rownum |
+----+------+-------+--------+
| 5 | m1 | MT | -1 |
| 6 | m2 | MT | -1 |
| 1 | a1 | NY | -1 |
| 2 | a2 | NY | -1 |
| 3 | a3 | NY | -1 |
| 4 | a4 | NY | -1 |
| 10 | s1 | SC | 1 |
| 11 | s11 | SC | 2 |
| 8 | s2 | SC | 3 |
| 9 | s4 | SC | 4 |
| 7 | s8 | SC | 5 |
+----+------+-------+--------+
那为什么派生表呢?因为我们必须引入一个变量作为我们的计数器。我们使用cross join
的唯一目的是将变量放入整个事物中。在解析派生表之后,我们将其结果折叠成包裹它的正常Update with a Join
模式。
当然,正如用户FirstOne所说,我们可以在某些情况下使用Update ... order by
。以上是我为此提出的。
哦,重申一下,派生表通常用于清理我们的自定义信息并将其折叠到查询的大部分内。