【发布时间】:2018-08-24 15:56:11
【问题描述】:
希望通过一个查询来获取数据,但列是基于所选值的动态。
所以我的表看起来像这样(使用 MySql):
CREATE TABLE 'users' (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL
)
CREATE TABLE `income` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user` int(11) NOT NULL,
`day` int(11) NOT NULL DEFAULT '0',
`action_a` decimal(10,2) NOT NULL DEFAULT '0.00',
`action_b` decimal(10,2) NOT NULL DEFAULT '0.00',
`action_c` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
)
CREATE TABLE `given` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`day` int(11) DEFAULT NULL,
`to_user` int(11) NOT NULL,
`from_user` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
)
想要进入一个如下所示的查询表:
+------------+--------------+----------+----------+----------+
| day | action_a | action_b | action_c | user_B | user_C |
+------------+--------------+----------+----------+----------+
| 123 | 123.01 | 123.01 | 123.01 | 123.01 | -123.01 |
| 122 | 324.02 | 234.01 | 123.01 | -123.01 | -123.01 |
| 121 | 987.00 | 345.01 | 123.01 | 123.01 | -123.01 |
| 120 | 9393.01 | 456.01 | 123.01 | -123.01 | -123.01 |
| 119 | 0.00 | 567.01 | 123.01 | -123.01 | -123.01 |
...
用户列中的负值表示用户给了其他用户
目前我正在执行 3 个单独的查询,然后合并数据,但我当前的查询如下所示:
获得基于行动的收入
Select action_a, action_b, action_c From income i Join users u on u.id=i.user Where u.name='%s' and i.day=%i Order by i.id desc
收到货
Select u2.name 'from', amount From given g Join users u on u.id = to_user Join users u2 on u2.id = from_user Where u.name='%s' and amount <> 0.0 Order by g.id
得到给予
Select u2.name 'to', amount From given g Join users u on u.id = from_user Join users u2 on u2.id = to_user Where u.name='%s' and amount <> 0.0 Order by g.id desc
【问题讨论】:
-
你可以为表格添加一些数据吗?带有示例数据的 SQLFiddle 链接也将非常有帮助。
-
同意,此处需要起始样本数据(或者,也许您如何合并数据),尤其是对于来自/来自用户的数据。请注意,我希望这是某种形式的运行求和/计算查询,MySQL 缺少内置运算符来很好地执行(也就是说,我希望查询通常通过窗口函数执行)
-
@clinomaniac 添加了 sql fiddle 链接
-
user_B和user_C的预期值是多少? -
这种问题是设计不佳的症状,所以认真考虑修改你的架构设计
标签: mysql sql select join create-table