我正在为某个私有站点创建数据库。在数据库中,我有一个名为times的表,可以在其中保存用户名和用户空闲的时间。桌子看起来像这样。
|uid |Monday|Tuesday |... |Saturday |Sunday |t12|t13|t14|...|t19|t20
_____________________________________________________________________
uid 是用户名, t12-t20 是小时( t16 = 1 , 星期一 = 1 表示该用户在星期一16点有空。
一行的示例为:
|alex1|1|1|0|0|0|0|1|0|0|0|0|0|1|1|1|1|
这意味着用户 alex1 在周一,周二和周日的17、18、19和20点免费。
表中可以有多个用户,某些用户可以有多个用户。像,用户alex1可以在更多行中具有不同的保存时间。 (示例:一行意味着他在星期一和星期五15点以后有空,但在另一行中,他在星期六的14点,17点和20点有空)
示例:
gordon | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
gordon | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
第一行表示:gordon用户在星期一和星期二12点是免费的。第二行表示:gordon用户在星期三13点是免费的
问题是:
如何进行遍历表格并给出结果的查询:
Day | t12 | t13 | t14 | t15 | t16 | t17 | t18 | t19 | t20 |
________________________________________________________________
Monday 5 4 8 8 8 4 0 0 4
Tuesday 2 2 2 2 2 1 0 0 2
Wednesday 10 10 10 2 8 10 8 7 7
Thursday 5 4 8 8 8 4 0 1 4
Friday 5 4 3 7 8 4 9 0 4
Saturday 8 9 8 3 9 4 3 0 4
Sunday 1 4 8 8 1 4 0 9 3
这意味着:星期一14点有8个免费用户,或星期五20点有4个免费用户。
答案 0 :(得分:1)
一个更好的设计示例是使用如下表格:
availability
user day time
1 1 16
这可能不是最好的解决方案,但是它对您当前的设置有很大的改进。
答案 1 :(得分:-1)
您可以计算按日计算的结果,然后按如下所示使用union-
SELECT 'Monday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Monday = 1
UNION ALL
SELECT 'Tuesday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Tuesday = 1
UNION ALL
SELECT 'Wednesday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Wednesday = 1
UNION ALL
SELECT 'Thursday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Thursday = 1
UNION ALL
SELECT 'Friday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Friday = 1
UNION ALL
SELECT 'Saturday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Saturday = 1
UNION ALL
SELECT 'Sunday' AS Day,
SUM(t12) t12,SUM(t13) t13,SUM(t14) t14,SUM(t15) t15,SUM(t16) t16,
SUM(t17) t17,SUM(t18) t18,SUM(t19) t19,SUM(t20) t20
FROM your_table WHERE Sunday = 1