由于我是SQL的新手,我不确定如何表达我的问题。这不应该太难。这是场景。
我有3张桌子:
客户
id,
contact
subscribers_from_x
customer_id
subscriber_name
subscribers_from_y
customer_id,
subscriber_name
这是一个问题:
现在,我想选择
customer.id
来自subscriber.id的次数/次数发生在subscriber_from_x
来自subscriber.id的次数/次数发生在subscriber_from_y
来自这3个表
我试过了GROUP_BY COUNT(*)
但没有弄明白。感谢
答案 0 :(得分:1)
我可能会使用两个单独的子查询,这些子查询按订阅者聚合x和y表的计数:
SELECT t1.id,
t1.contact,
COALESCE(t2.x_count, 0) AS subscribers_from_x,
COALESCE(t3.y_count, 0) AS subscribers_from_y
FROM customers t1
LEFT JOIN
(
SELECT customer_id, COUNT(*) AS x_count
FROM subscribers_from_x
GROUP BY customer_id
) t2
ON t1.id = t2.customer_id
LEFT JOIN
(
SELECT customer_id, COUNT(*) AS y_count
FROM subscribers_from_y
GROUP BY customer_id
) t3
ON t1.id = t3.customer_id
答案 1 :(得分:1)
SELECT DISTINCT(users.id),count(x.customer_id) 'X count',count(y.customer_id) 'Y Count'
FROM customers
LEFT JOIN subscribers_from_x x ON customers.id = x.customer_id
LEFT JOIN subscribers_from_y y ON customers.id = y.customerid
GROUP BY customers.id,subscribers_from_x.pk_col -- primary key col of subscribers_from_x
它将为您提供所需的输出