Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

mysql - Request for the existence of links

How to make a quick selection and get the number of those users who have already invited at least someone?
I tried, suffered, it doesn't work:

SELECT COUNT(u.id) as `count` 
FROM users u 
LEFT JOIN users u1 ON u1.id=u.ref 
LEFT JOIN users u2 ON u2.id=u1.ref

You need to make 1 sql, and it turns out that only the id and ref columns are used.
Those users who haven't invited anyone shouldn't be in the count.

Is it possible to do this or will it be necessary to use cycles and make more requests?

structure is simple - you need to get those who have invited at least someone

For this structure, it should look like this:

1 - invited? Yes!
2 - invited? Yes!
3 - invited? No!
4 - invited? Yes!
5 - invited? Yes!
6 - invited? Yes!
7 - invited? No!

Only 5.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Previous answer was based on an unclear definition of how ref was used. This should give you what you want:

SELECT COUNT(u.id) as `count` 
FROM users u 
WHERE EXISTS (SELECT 1 FROM users u1 WHERE u1.ref = u.id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...