gpt4 book ai didi

mysql - 修改 MySQL 查询或在 PHP 中运行

转载 作者:行者123 更新时间:2023-11-29 10:13:53 25 4
gpt4 key购买 nike

我正在尝试运行查询来查找我应该宣传哪些广告资源以及应该运行哪些广告系列,以便我可以移动该广告资源。

我有三个表:

  • campaigns 列出了我可以运行的不同广告系列,每个广告系列都有一个唯一的 ID。有些广告系列仅宣传一件商品,有些广告系列则宣传多种商品。
  • 库存包含我库存的所有商品以及这些商品的数量。
  • campaign_to_inventory 将唯一的广告系列 ID 与库存项目相匹配。

事件:

name         | id
-------------|---
blue-widgets | 1
gluten-free | 2
gadget | 3

库存:

item   | qty
-------|----
thing1 | 0
thing2 | 325
thing3 | 452
thing5 | 123
thing7 | 5

campaign_to_inventory:

id | item
---|-------
1 | thing1
1 | thing2
1 | thing5
2 | thing1
2 | thing3
3 | thing7

我想运行一个查询来查找我可以在拥有所需库存的情况下运行的所有广告系列。我当前正在运行此查询:

SELECT * FROM `campaigns` LEFT JOIN `campaign_to_inventory` ON `campaigns`.`id` = `campaign_to_inventory`.`id` LEFT JOIN `inventory` ON `campaign_to_inventory`.`item` = `inventory`.`item`

返回结果:

name         | id | item   | qty
-------------|----|--------|----
blue-widgets | 1 | thing1 | 0
blue-widgets | 1 | thing2 | 325
blue-widgets | 1 | thing5 | 123
gluten-free | 2 | thing1 | 0
gluten-free | 2 | thing3 | 452
gadget | 3 | thing7 | 5

我应该使用 PHP 处理此数据以仅查找所有商品数量都大于最小阈值的营销事件,还是有办法修改查询以限制其中的行?是否有一条经验法则规定我什么时候可以/应该在其中一种而不是另一种中做到这一点?

最佳答案

无需在 PHP 中处理数据。

实现此目的的一种方法是选择项目数量小于阈值的 campaign_to_inventory.id 列,如下所示:

SET @min_qty = 1;
SELECT `c_to_i`.`id` FROM `campaign_to_inventory` AS `c_to_i`
INNER JOIN `inventory` ON `inventory`.`item` = `c_to_i`.`item`
WHERE `inventory`.`qty` <= @min_qty;

...然后从 campaign_to_inventory 进行左外连接,如下所示:

SET @min_qty = 1;
SELECT `id`, `name` FROM `campaigns`
LEFT JOIN (
/* Table of campaigns which contain items with not enough qty*/
SELECT `c_to_i`.`id` FROM `campaign_to_inventory` AS `c_to_i`
INNER JOIN `inventory` ON `inventory`.`item` = `c_to_i`.`item`
WHERE `inventory`.`qty` <= @min_qty
) AS `campaigns_with_not_enough_items`
ON `campaigns`.`id` = `campaigns_with_not_enough_items`.`id`
WHERE `campaigns_with_not_enough_items`.`id` is NULL;

结果应该是一个包含所需库存库存的营销事件表格。

顺便说一句,您应该将 campaign_to_inventory.id 列重命名为 campaign,因为名称 id 暗示该列是主键对于表。

关于mysql - 修改 MySQL 查询或在 PHP 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com