dtpa98038 2019-02-11 20:03
浏览 38

MySQL同一查询+ PHP中每一行的特定条件

Please consider my tables

  • store - table with information of all my stores
  • zone - An alias table with zone_id and the name of the zone.
  • store_zone - Table that contains the information when a store was changed to a different zone.
  • cashdesk - table with local_id that contains information about the income for each day and each store

store_zone table:

+----+----------+---------+-------------+
| id | store_id | zone_id | modified_at |
+----+----------+---------+-------------+
|  1 |        1 |       2 | 2019-01-01  |
|  2 |        1 |       1 | 2019-01-04  |
|  3 |        2 |       4 | 2019-01-03  |
+----+----------+---------+-------------+
  • store_id is the foreign key for my local table id
  • store table also contains a fk for zone_id
  • zone_id is the foreign key for my zone table id

Now consider my problem:

  • I need to select all stores
  • get the sum(income) per row (stores)
  • filter by zone
  • consider only incomes that correspond to the local_zone table between dates. (if I select the whole month and a zone was changed the day 15.. I only care about the 15 first days). I can use php to help build it.

something like:

$zone_modified_dates = //result of 
"SELECT modified_at 
FROM store_zone 
WHERE zone_id = 1 AND store_id = 1"
$zone_modified_dates = '2019-01-04'


SELECT sum(income) from cashdesk c
inner join store s ON s.id = c.store_id
inner join store_zone sz ON (sz.store_id = s.id AND sz.zone_id = z.id
WHERE zone_id = 1 
AND cashdesk created_at >= '2019-01-01' 
AND cashdesk created_at >= '2019-01-10'
AND //IF ZONE WAS CHANGED IN THIS CREATED_AT BETWEEN DATES ONLY CONSIDER THE DAYS THAT THE SPECIFIC ROW STORE WAS CONSIDERED ZONE 1
GROUP BY s.id

Thanks in advance.

@edited for better explanation of the problem.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
    • ¥15 lingo18勾选global solver求解使用的算法
    • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
    • ¥20 测距传感器数据手册i2c