我试图展示商家以及最高折扣优惠。但我仍然希望展示没有报价的企业。
商家存储在<tr v-for="item in items">
<td>
<span id="TRIGGER" @click="visible = item.name">{{item.name}}</span>
<div id="SHOW-HIDE-DIV" v-show="visible === item.name"></div>
</td>
</tr>
business_tb
这些商家提供的折扣存储在business_id | business_name
------------+---------------
1 | aaa
2 | bbb
3 | ccc
deal_offer_tb
和折扣类型存储在deal_offer_id | business_id | deal_id
--------------+-------------+----------
1 | 1 | 3
2 | 1 | 2
3 | 2 | 0
4 | 1 | 1
5 | 3 | 3
。
deal_tb
所以我想要的显示应该是这样的:
deal_id | discount
--------+----------
1 | 40%
2 | 30%
3 | 20%
4 | 10%
但是我目前的查询:
1 | aaa | 40%
2 | bbb | ---
3 | ccc | 20%
我只得到:
SELECT a.business_id, a.business_name, c.discount
FROM business_tb a
LEFT JOIN (SELECT min(deal_id) AS deal_id, business_id FROM deal_offer_tb GROUP BY business_id) b ON a.business_id = b.business_id
LEFT JOIN deal_tb c ON b.deal_id = c.deal_id
它不显示没有提供折扣的商家。
我怎么想得到我想要的输出?
更新:我不知道之前发生了什么,但我的查询按照我想要的方式运行。感谢那些回答的人的努力。欣赏它,大时间!
答案 0 :(得分:1)
我会通过使用子查询来查找每个业务的最大折扣,加入deal_offer_tb
和deal_tb
表。然后,将此子查询连接到business_tb
表以获取最终结果。请注意,我使用初始LEFT JOIN
来说明某个商家甚至可能没有与之相关的交易。在这种情况下,我为该业务分配了最大折扣0(这是有道理的,因为那时将适用完整的正常价格)。
SELECT
t1.business_id,
t1.business_name,
COALESECE(t2.max_discount, 0) AS max_discount
FROM business_tb t1
LEFT JOIN
(
SELECT t1.business_id, MAX(t2.discount) AS max_discount
FROM deal_offer_tb t1
INNER JOIN deal_tb t2
ON t1.deal_id = t2.deal_id
GROUP BY t1.business_id
) t2
ON t1.business_id = t2.business_id
答案 1 :(得分:1)
此查询基本上是您的查询(带表别名):
SELECT b.business_id, b.business_name, d.discount
FROM business_tb b LEFT JOIN
(SELECT MIN(deal_id) AS deal_id, business_id
FROM deal_offer_tb dot
GROUP BY business_id
) dot
ON b.business_id = dot.business_id LEFT JOIN
deal_tb d
ON d.deal_id = dot.deal_id;
根据LEFT JOIN
的定义,无论business_tb
子句的其余部分是否存在匹配,它都会将所有行保留在FROM
中。您没有其他过滤(通过WHERE
)或聚合。因此,这应返回business_tb
中的所有行。
答案 2 :(得分:0)
以下是进行查询的一种方法:
SELECT
a.business_id, a.business_name, b.max
FROM business_tb a
INNER JOIN (
SELECT
c.business_id, MAX(d.discount) AS max
FROM deal_offer_tb c
LEFT JOIN deal_tb d ON c.deal_id = d.deal_id
GROUP BY c.business_id
) b ON a.business_id = b.business_id;
deal_id
中没有deal_tb
0,所以我认为null
deal_offer_id
为COMPUTE count=XDATE.WEEK(date).
。