sql查询以查找可用日期

时间:2015-12-18 07:06:05

标签: mysql sql join

我不知道这有解决方案,或者我不知道要使用哪个搜索字词。这是我的问题。我有4 Tables

  • Available - 可用日期。
  • School_menu - 哪个菜单属于哪所学校。
  • Menu - 由项目组成的菜单。
  • Item - 常用订购商品。

我一直在使用以下查询来生成可用日期。所以有人可以订购单日期。例如:2015-12-17

SELECT DISTINCT
        *
FROM    Available AS a
        JOIN School_menu AS sm ON a.school_menu_id = sm.school_menu_id
        JOIN Menu AS m ON m.menu_id = sm.menu_id
        JOIN Item AS it ON m.menu_id = it.menu_id
WHERE   ( a.available_date BETWEEN '2015-12-27'
                           AND     '2016-02-05' )
        AND sm.sch_id = '7';

最近,我被告知要添加其他功能。详细说明,

产品,

  • 披萨
  • 海底

如果用户可以在12月12日订购披萨,则可以在接下来的几天内再次按下按钮。如果披萨可以在接下来的几天内通过加入菜单的可用日期进行查询,则可获得第13届第14届。 1项不是问题。 2项目怎么样?我该如何编写查询?它首先看起来并不复杂。所以,我写了一个查询

SELECT DISTINCT
        *
FROM    Available AS a
        JOIN School_menu AS sm ON a.school_menu_id = sm.school_menu_id
        JOIN Menu AS m ON m.menu_id = sm.menu_id
        JOIN Item AS it ON m.menu_id = it.menu_id
WHERE   ( a.available_date BETWEEN '2015-12-27'
                           AND     '2016-02-05' )
        AND sm.sch_id = '7'
        AND it.item_id IN ( 28, 31 )
        AND a.available_date != DATE(( '2016-01-05' ));
像这样,搞砸了整个订购系统。

如何编写正确的查询!!感谢

补充说,SQL Fiddle     http://sqlfiddle.com/#!9/3f44d/1

1 个答案:

答案 0 :(得分:1)

我能够通过将可用日期分组在一起并计算组的数量并动态调整有计数来修复此查询。

SELECT DISTINCT *, COUNT(*) 
   FROM Available AS a JOIN School_menu AS sm ON 
     a.school_menu_id = sm.school_menu_id JOIN Menu AS m ON 
     m.menu_id = sm.menu_id JOIN Item AS it ON m.menu_id = it.menu_id 
WHERE (a.available_date BETWEEN '2015-12-27' AND '2016-02-05') 
 AND sm.sch_id = '7' AND it.item_id IN (26, 25, 28) 
 AND a.available_date != DATE(('2016-01-04')) GROUP BY a.available_date
HAVING COUNT (a.available_date) > XX
xx = Dyamic Count