mysql - 在 mysql select 查询中使用变量而不是字段名

标签 mysql mysql-variables

我已经搜索了很多,但我不知道该怎么做,如果可能的话......

我有这张表:

CREATE TABLE bilanci (
  id              int AUTO_INCREMENT NOT NULL,
  medicoid        int NOT NULL,
  `1`             int NOT NULL DEFAULT 0,
  `2`             int NOT NULL DEFAULT 0,
  `3`             int NOT NULL DEFAULT 0,
  `4`             int NOT NULL DEFAULT 0,
  `5`             int NOT NULL DEFAULT 0,
  `6`             int NOT NULL DEFAULT 0,
  `7`             int NOT NULL DEFAULT 0,
  `8`             int NOT NULL DEFAULT 0,
  `9`             int NOT NULL DEFAULT 0,
  `10`            int NOT NULL DEFAULT 0,
  `11`            int NOT NULL DEFAULT 0,
  `12`            int NOT NULL DEFAULT 0,
  conguagliodic   decimal(10,2),
  totbilancianno  int DEFAULT 0,
  totpagato       decimal(12,2),
  totdapagare     decimal(12,2),
  conguaglio      decimal(10,2),
  rifanno         int NOT NULL,
  pvimun          decimal(10,4) NOT NULL DEFAULT 9.4432,
  PRIMARY KEY (id)
) ENGINE = InnoDB;

以数字命名的字段对应于月份,我需要进行如下选择:

select medicoid, (month(curdate()) -2), totdapagare from bilanci

其中 (month(curdate()) -2) 对应于我需要选择的字段。

这可能吗?

最佳答案

我建议你标准化你的数据库结构,你可以有一个像这样的表:

CREATE TABLE bilanci (
  id              int AUTO_INCREMENT NOT NULL,
  medicoid        int NOT NULL,
  conguagliodic   decimal(10,2),
  totbilancianno  int DEFAULT 0,
  totpagato       decimal(12,2),
  totdapagare     decimal(12,2),
  conguaglio      decimal(10,2),
  pvimun          decimal(10,4) NOT NULL DEFAULT 9.4432,
  PRIMARY KEY (id)
) ENGINE = InnoDB;

和第二个表 bilanci_month:

create table bilanci_month (
  id int auto_increment,
  bilanci_id int,
  rifanno int NOT NULL,
  month int NOT NULL,
  value int)

(bilanci_id可以定义为bilanci_month的外键),那么你的选择查询将是这样的:

select
  b.medicoid,
  coalesce(bm.value, 0),
  b.totdapagare from bilanci
from
  bilanci b left join bilanci_month bm
  on b.id = bm.bilanci_id and bm.month = month(curdate())-2

另外,请注意month(curdate())-2,如果月份是一月或二月会发生什么?您必须实现一些逻辑来获取例如上一年的 11 月或 12 月(并将此逻辑添加到您的联接中)。

关于mysql - 在 mysql select 查询中使用变量而不是字段名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40463785/

相关文章:

mysql - 禁用 ONLY_FULL_GROUP_BY mysql 8 Ubuntu 20.04 LTS

php - 在 ZF2 中使用 WHERE 和 JOIN 进行更新

MySQL 在 LOCATE 中使用用户定义的变量时出现非法的排序规则混合

mysql - 从多 SELECT 子查询返回多行

mysql - 列出运行时可以修改的所有变量

php - 如何选择 mysql 两列取最后 200 个 id order desc,然后通过 count desc 获得 5 个 order 以获得最佳性能

php - 需要通过唯一用户标识、最大轮次从 mysql 中提取数据,然后按另一个值排序

mysql - 获取每组分组结果的前 n 条记录

mysql分组排名与领带

php - 获取主题 id 的类别