S
S
Shuhratjon Djumaev2016-03-19 20:14:34
PHP
Shuhratjon Djumaev, 2016-03-19 20:14:34

Need to improve sql query.?

I have these tables:
Groups:
id
name
and
Group Members:
id
groupId
memberId
We have a user id.
You need to get a list of groups to which he is subscribed with the number of group subscribers and the name of the group.
I have the following sql query to get a list of groups, but I can't get the number of group subscribers:

SELECT g.gid, g.name
  FROM groups g, groupmembers gm
  WHERE gm.memberId = 1 AND g.gid = gm.groupId

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Bykov, 2016-03-20
@shuhratjon

SELECT g.gid, g.name, (SELECT COUNT(*) FROM groupmembers m WHERE m.gid = g.groupId) AS CoungGM
  FROM groups g, groupmembers gm
  WHERE gm.memberId = 1 AND g.gid = gm.groupId

R
Rsa97, 2016-03-19
@Rsa97

COUNT()
JOIN

A
Alexey, 2016-03-19
@k1lex

Get the group list like this

select 
      g.gid, 
      g.name
from  groups g
inner join  groupmembers gm ON gm.memberId = 1 AND g.gid = gm.groupId

Number of subscribers for each group:
select 
      g.name, 
   COUNT(gm.id) as CountGM
from  groups g
inner join  groupmembers gm ON gm.memberId = 1 AND g.gid = gm.groupId
group by g.name

And better spend a couple of hours on SQL tutorial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question