有没有办法计算已离开连接的数据透视表,然后再次在数据透视表上运行where子句以过滤掉不需要的其余部分?
以下是我到目前为止:
SELECT *
FROM
(
SELECT COUNT(user_id) as Count
FROM group_buys
) GroupBuy
LEFT JOIN group_buy_users GroupBuysUser
ON GroupBuysUser.group_buy_id = GroupBuy.id
WHERE GroupBuysUser.user_id = {$this->Auth->user('id')}
我找到了解决方案:
SELECT *
FROM group_buys GroupBuy
LEFT JOIN group_buy_users GroupBuysUser
ON GroupBuysUser.group_buy_id = GroupBuy.id
LEFT JOIN (
SELECT group_buy_id, COUNT(user_id) as Count
FROM group_buy_users
GROUP BY group_buy_id
) GroupBuysUserCount
ON GroupBuysUserCount.group_buy_id = GroupBuy.id
LEFT JOIN group_buy_merchant_offers GroupBuysMerchantOffer
ON GroupBuysMerchantOffer.group_buy_id = GroupBuy.id
WHERE GroupBuysUser.user_id = {$this->Auth->user('id')}
GROUP BY GroupBuy.id
HAVING GroupBuy.expiry_date > NOW()
ORDER BY GroupBuysMerchantOffer.bid_price ASC
基本上我只需要做一个LEFT JOIN一个虚拟表,它已经在其id上使用group buy计数,然后user_id属于user的子句然后再在Groupbuy.id上进行分组以消除重复。我添加了到期,因为我必须删除所有过期的旧组件,但是这会从group_buy_users表中添加组用户的数量,然后再添加group_buy_users表,因此我可以检索其他详细信息。