在多个表上进行左连接,其中任何一个表都可以是 master

Left Joins on several tables where any one of them can be master

我已经简化了实际的实时代码,因为我不想用不相关的数据溢出 post。

我(遗憾地)有七个 tables,每个工作日一个,包含完全相同的信息,除了两个项目,即报纸标题和客户应该收到的报纸数量。现在任何客户都可以拥有任意数量的报纸(从一个标题一直到 20 个不同的标题)并且他们每天可以拥有任意数量的该标题的报纸(0 到大量)- 但是!问题来了——他们在任何一天的数量都可以为 0。 最后我需要的是:

Customer1, New York Times, 0, 7, 3, 2, 2, 10, 10

这表明 Customer1 在星期二想要 7 个纽约 Tiems(是的,我来自瑞典,一周确实从星期一开始),星期六需要 10 个,星期日需要 10 个 e.tc。 现在我拥有的 7 个不同的 table 如果客户在那一天没有任何文件,我现在将不包含任何信息,这意味着我不能这样做:

    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

因为星期一可能是这个特定客户没有任何文件的日子,因此根本不属于星期一 table。理论上他只能在 table 中的一个,我不知道是哪一个。

如何编写一个我不知道哪个是 "master" table 的连接??

您真的不需要知道哪个是 master table,您可以使用 UNION ALL 将所有结果组合成一个结果或派生 table。

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
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

是的,松鼠先于我。我只是太慢了。不应该尝试在弱 android phone 上编辑我的答案十分钟 ;-).

但是,正如 freakyhat 已经说过的,正如您从我的解决方案中派生的 table 中看到的那样,将所有值存储在 one[=16 中是个好主意=] table ...