0

我正在尝试将一些数据从旧表转换为新结构,我需要将单个键 ID 转换为复合键 ID,这给我带来了一些麻烦:

我的表(简化):

CREATE TABLE `tmplt_spoergsmaal` (
  `SpID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `lbnr` int(10) unsigned DEFAULT NULL,
  `SpTekst` text,
  `SpTitel` varchar(100) NOT NULL DEFAULT '',
  `fk_Naeste_Sp` int(10) unsigned DEFAULT NULL,
  `kontrol` tinyint(3) unsigned NOT NULL DEFAULT 0,
  `kontrol_kilde` int(10) unsigned NOT NULL DEFAULT 0,
  FOREIGN KEY (kontrol_kilde) 
    REFERENCES tmplt_spoergsmaal(SpID)
    ON DELETE ignore
)

样本数据:

请注意,SPID 是顺序的

+--------+--------+-----------+-----------+------------+-----------------+
|  SpID  |  lbnr  |  SpTekst  |  SpTitel  |   kontrol  |  kontrol_kilde  | 
+--------+--------+-----------+-----------+------------+-----------------+
|  9000  |  100   | blablabla | title1    |      0     |     null        |
+--------+--------+-----------+-----------+------------+-----------------+
|  9001  |  101   | blablabla | title2    |      0     |     null        |
+--------+--------+-----------+-----------+------------+-----------------+
|  9002  |  102   | blablabla | title3    |      0     |     null        |
+--------+--------+-----------+-----------+------------+-----------------+
|  9003  |  103   | blablabla | title4    |      1     |       9000      |
+--------+--------+-----------+-----------+------------+-----------------+
|  9004  |  104   | blablabla | title5    |      1     |       9001      |
+--------+--------+-----------+-----------+------------+-----------------+

我正在重新设计数据库,并使用lbnr列而不是kontrol_kilde列。我的初步查询是这样的:

SELECT spid, lbnr, kontrol, kontrol_kilde, (lbnr- (spid - kontrol_kilde)* kontrol)* kontrol AS k
FROM tmplt_spoergsmaal;

这解决了我的问题,但是在某个时候出现了一个问题(因为减法的翻转(spid - kontrol_kilde已经成为kontrol_kilde - spid),这使得部分等式为负。由于该列是无符号的,这导致了一个错误:

Error Code: 1690. BIGINT UNSIGNED value is out of range in

我的问题:

我可以“转换”别名列中的列k,使其成为int而不是unsigned int吗?

4

1 回答 1

1

好吧,您cast()可以signed

SELECT spid, lbnr, kontrol, kontrol_kilde,
       cast(lbnr - (spid - kontrol_kilde) * kontrol)* kontrol as signed) AS k
FROM tmplt_spoergsmaal;
于 2019-01-27T22:05:00.823 回答