R
R
Relapse2018-04-03 13:25:27
MySQL
Relapse, 2018-04-03 13:25:27

How to count values ​​from two MySQL tables?

Hello!
There is a request like this:

SELECT a.parent_id FROM users a WHERE a.user_id != 0 AND a.parent_id != 0 GROUP BY a.parent_id;

which displays the referrer ID from the affiliate program.
It is also necessary to display the number of referrals for each referrer.
Query that displays referrals of a specific referrer:
SELECT * FROM referals a WHERE a.parent_id = ИД_РЕФЕРЕРА

Question: how to combine these two codes?
Tried like this:
SELECT a.parent_id, COUNT(b.id) AS count_refs FROM users a, referals b WHERE a.parent_id = b.parent_id AND a.user_id != 0 AND a.parent_id != 0 GROUP BY a.parent_id

but not quite correct values ​​are displayed (somewhere they match, somewhere not).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Shelemetiev, 2018-04-03
@Relapse

For example, like this:

SELECT distinct a.parent_id, b.cnt FROM users a 
left join (
SELECT parent_id, count(id) cnt FROM referals group by parent_id
) b on a.parent_id = b.parent_id
WHERE a.user_id != 0 AND a.parent_id != 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question