正在 mysql 查询中重新键入别名列

Retyping alias column in mysql query

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

我的table(简体):

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

我的问题:

我可以 "cast" 别名列 k 中的列,以便它是 int 而不是 unsigned int 吗?

嗯,你可以 cast() 作为 signed:

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