我已经简化了我的实际实时代码,因为我不想用无关数据溢出这篇文章。
我(遗憾地)有七张桌子,每个工作日一张,包含完全相同的信息,除了两个项目,即报纸标题和客户应该收到的报纸数量。现在任何一个客户都可以拥有任意数量的报纸(从单一的标题,一直到20种不同的标题),每天都可以有任意数量的报纸(0到大量) - 但是!这里有踢球者 - 他们在任何一天都可以获得0。 我最终需要的是:
Customer1, New York Times, 0, 7, 3, 2, 2, 10, 10
这表明Customer1在星期二需要7个New York Tiems(是的,我来自瑞典,星期一是从星期一开始),星期六10点,星期日10点e.tc. 现在我现在拥有的7个不同的表格根本不包含任何信息,如果客户当天没有任何论文,这意味着我不能这样做:
select t1.name, t1.title, t1.amount, t2.amount,
t3.amount, t4.amount, t5.amount, t6.amount,
t7.amount
from table_mon t1
left join table_tue t2 on t2.name = t1.name
left join table_wen t3 on t3.name = t1.name
left join table_thu t4 on t4.name = t1.name
left join table_fri t5 on t5.name = t1.name
left join table_sat t6 on t6.name = t1.name
left join table_sun t7 on t7.name = t1.name
因为星期一可能是这个特定客户没有任何纸张的日子,因此根本不是星期一表的一部分。从理论上讲,他只能在其中一个表格中,我不知道哪一个。
如何编写一个我不知道哪个是“主”表的连接?
答案 0 :(得分:1)
您真的不需要知道哪个是master
表,您可以使用UNION ALL将其全部合并到一个结果或派生表中。
SELECT name, title, SUM(MON), SUM(TUE), SUM(WED), SUM(THU)
FROM
(
SELECT name, title, amount as MON, NULL as TUE, NULL as WED, NULL as THU, . . .
FROM table_mon
UNION ALL
SELECT name, title, NULL as MON, amount as TUE, NULL as WED, NULL as THU, . . .
FROM table_tue
UNION ALL
SELECT name, title, NULL as MON, NULL as TUE, amount as WED, NULL as THU, . . .
FROM table_wed
) d
GROUP BY name, title
答案 1 :(得分:1)
select name, title,
sum(a1) mon, sum(a2) tue, sum(a3) wed, sum(a4) thu, sum(a5) fri,
sum(a6) sat, sum(a7) sun from (
select name,title,amount a1,0 a2,0 a3,0 a4,0 a5,0 a6,0 a7 FROM table_mon union all
select name,title,0,amount,0,0,0,0,0 FROM table_tue union all
select name,title,0,0,amount,0,0,0,0 FROM table_wed union all
select name,title,0,0,0,amount,0,0,0 FROM table_thu union all
select name,title,0,0,0,0,amount,0,0 FROM table_fri union all
select name,title,0,0,0,0,0,amount,0 FROM table_sat union all
select name,title,0,0,0,0,0,0,amount FROM table_sun
) week
group by name,title
是的,松鼠已经打败了我。我太慢了。不应该尝试在弱智能手机上编辑我的答案十分钟; - )。
但是,正如freakyhat已经说过的那样,正如你在我的解决方案中从派生表中看到的那样,将所有值存储在 one 表中是个好主意......