这让我困惑了几个小时。
所以我有一个活动表和一个供应商表。供应商可能有多个活动。如果供应商有足够的积分,我想选择所有广告系列。
问题是我不知道将从同一个供应商那里选择多少个广告系列,这意味着该供应商可能仍有两个广告系列的积分,但其余的则没有。
例子
tblvendors
+---------+------------+---------------+
|vendorId | vendorName | vendorCredits |
+---------+------------+---------------+
| 1 | a | 5 |
| 2 | b | 100 |
+---------+------------+---------------+
tblproducts
+-----------+---------------+------------+
| productId | productName | vendorId |
+-----------+---------------+------------+
| 1 | c | 1 |
| 2 | e | 2 |
| 3 | f | 1 |
| 4 | g | 1 |
| 5 | h | 1 |
+-----------+---------------+------------+
tblcampaigns
+------------+---------------+------------+
| campaignId | productId | vendorId |
+------------+---------------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 5 | 1 |
+------------+---------------+------------+
现在考虑到每次选择一行时,供应商都会失去 2 个积分,因为供应商“a”只剩下 5 个积分,只有活动 1 2 和 3 应该返回。
我目前的查询是这样的:
SET @maxCampaignId = (SELECT MAX(campaignId) FROM tblCampaigns);
SELECT
@maxCampaignId,
t0.campaignId,
t0.productId,
productName,
productDescription,
productImage,
(CASE WHEN campaignId > (SELECT configValue FROM tblconfiguration WHERE configKey = 'lastHomeCampaignId')
THEN campaignId ELSE campaignId + @maxCampaignId END) AS orderField
FROM tblcampaigns AS t0
INNER JOIN tblproducts AS t1 ON t0.productId = t1.productId
INNER JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId
WHERE
campaignType = 'homeFeature' AND
t0.isActive = 1 AND
t2.vendorCredits > (SELECT configValue FROM tblconfiguration WHERE configKey = 'campaignHomeFeatureCost' LIMIT 1)
ORDER BY orderField ASC
LIMIT 4
如您所见,问题在于比较 vendorCredits 的行。显然,查询选择的广告系列超出了供应商的承受能力。
我想避免在 PHP 中执行此操作,因为我认为应该可以直接从数据库中执行此操作。