如何在不真正加入 table 的情况下通过联接获取某些字段值?

How can I take certain field value with a join without really joining that table?

好吧,我有一个来自客户的数据库,其中的表关系不好,很乱。获取我需要的信息的问题是我需要关联表的字段与我将要使用的表无关。

我会说清楚的:

有 3 个表:访问、咖啡和付款。

Table 咖啡有 payment_id。 Table 次访问了 coffee_id。 Table 付款没有 ID!!

我想知道有多少人喝了咖啡,每杯咖啡支付了多少款项..

结果应该是这样的:

访问 |咖啡 |付款
8234 |摩卡 | 829

那么,我如何才能知道所有已支付的款项、它是什么咖啡以及它有多少次访问?

可能很明显,但我有点不知所措。

感谢大家的帮助!

获得每杯咖啡的访问量:

SELECT c.name AS coffee, IFNULL(count(v.coffee_id), 0) AS visits
FROM coffees AS c
LEFT JOIN visits AS v ON c.id = v.coffee_id
GROUP BY c.id

要获得每杯咖啡的付款:

SELECT c.name AS coffee, IFNULL(count(p.id), 0) AS payments
FROM coffees AS c
LEFT JOIN payments AS p ON c.payment_id = p.id
GROUP BY c.id

要在一个查询中同时获取它们:

SELECT coffee, MAX(visits) AS visits, MAX(payments) AS payments
FROM (
    SELECT c.name AS coffee, IFNULL(count(v.coffee_id), 0) AS visits, 0 AS payments
    FROM coffees AS c
    LEFT JOIN visits AS v ON c.id = v.coffee_id
    GROUP BY c.id
    UNION
    SELECT c.name AS coffee, 0 as visits, IFNULL(count(p.id), 0) AS payments
    FROM coffees AS c
    LEFT JOIN payments AS p ON c.payment_id = p.id
    GROUP BY c.id) x
GROUP BY coffee