所以我有两个表fooditems https://ibb.co/c2xrxF和order_fooditems(包含所有订购的食品)https://ibb.co/dEZJBa我怎样才能从食品表中获取所有食品,特别是max_plates是如果大于订购的食品数量,则delivery-advance_notice也大于当前时间。
例如如果食品项目的最大可用面积为5,并且已经订购了4个印版,那么只能再订购1个此商品的印版。如果订购了5个盘子,那么这道菜不应该在那里结果。用这个sql查询但没有得到任何结果
$value = date('Y-m-d H:i:s');
$query="SELECT * from fooditems where category_id = {$category['id']} and id in (SELECT * FROM fooditems fi JOIN order_fooditems ofi ON fi.id = ofi.fooditems_id WHERE fi.max_plates > ofi.quantity and (fi.delivery- fi.advance_notice)>('$value')";
已经尝试了一整天,但无法弄清楚正确的查询。任何建议都会很有帮助。谢谢。
答案 0 :(得分:0)
这可能会对你有所帮助。我想如果你试验下面的查询,你可以自己弄清楚delivery-advance_notice。
SELECT *,SUM(order_fooditems.quantity) AS totalqtyOrdered
FROM fooditems INNER JOIN order_fooditems ON fooditems.id=order_fooditems.fooditems_id
where category_id = {$category['id']}
GROUP BY fooditems.id
HAVING SUM(order_fooditems.quantity) < fooditems.max_plates
要获取没有任何订单的项目,请使用LEFT JOIN并在having子句中添加另一个OR条件
SELECT *,SUM(order_fooditems.quantity) AS totalqtyOrdered
FROM fooditems LEFT JOIN order_fooditems ON fooditems.id=order_fooditems.fooditems_id
where category_id = {$category['id']}
GROUP BY fooditems.id
HAVING (SUM(order_fooditems.quantity) < fooditems.max_plates) OR (order_fooditems.fooditems_id IS NULL);
但是,如果您在结果中仅需要itemName,则需要将上述查询放入子查询
SELECT itemName FROM
(SELECT a.id,a.max_plates,a.itemName,b.fooditems_id FROM fooditems a LEFT JOIN order_fooditems b ON a.id=b.fooditems_id GROUP BY a.id HAVING (SUM(b.quantity) < a.max_plates) OR (b.fooditems_id IS NULL))
AS subqueryTable;