目前我有两张包含一些数据的表格。第一个表格如下:
+----------------+-----------+
| name | member_id |
+----------------+-----------+
| Juice Box | 49432 |
| Rainsurge | 49631 |
| spiderpigrider | 50482 |
+----------------+-----------+
第二个表格如下:
+------------+-----------+
| recruit_id | bin(refs) |
+------------+-----------+
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
+------------+-----------+
我想像这样返回名称,总refs和member_id / recruit_id(仅列出至少有1个参考的用户)
+------------+-----------+------------+
| recruit_id | name | total_refs |
+------------+-----------+------------+
| 49631 | Rainsurge | 5 |
| 49432 | Juice Box | 5 |
+------------+-----------+------------+
select r.recruit_id,bin(r.refs),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
这返回了我的数据,但显然没有总计数和重复的名称/ ID
select r.recruit_id,count(bin(r.refs)),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
此返回的数据包含所有人的总数,但只有一个ID /名称
+------------+--------------------+-----------+
| recruit_id | count(bin(r.refs)) | name |
+------------+--------------------+-----------+
| 49432 | 10 | Juice Box |
+------------+--------------------+-----------+
这会返回数据,但不会再次计数
select distinct r.recruit_id,bin(r.refs),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
+------------+-------------+-----------+
| recruit_id | bin(r.refs) | name |
+------------+-------------+-----------+
| 49432 | 1 | Juice Box |
| 49631 | 1 | Rainsurge |
+------------+-------------+-----------+
非常感谢任何帮助或指导。我觉得我已经离这里很近但只是没有足够的能力使用SQL来获得它。谢谢!
答案 0 :(得分:1)
您必须使用group by
子句:
select r.recruit_id, ipb.name, count(bin(refs)) as total_refs
from refs as r
inner join syndicate_ipb.core_members as ipb
on ipb.member_id=r.recruit_id
group by r.recruit_id, ipb.name
having count(bin(refs)) >= 1
此group by r.recruit_id, ipb.name
会对结果进行分组,而having count(bin(refs)) >= 1
会认为它只返回至少有一个参考的成员
不要只根据您想要的列对列进行分组。即使MySql允许它,它也不是SQL Ansi模式,甚至MySql现在也遵守它。在select语句中使用与整列相关的聚合函数分组。
答案 1 :(得分:1)
你快到了。你最后错过了GROUP BY
条款。
<强>查询:强>
SELECT
r.recruit_id,
count(bin(r.refs)),
ipb.name
FROM refs AS r
INNER JOIN syndicate_ipb.core_members AS ipb
ON ipb.member_id = r.recruit_id
GROUP BY r.recruit_id;
注意:
如果bin(refs)
列始终包含值1,那么实际上您不需要保留该列。在这种情况下,您可以使用count(*)
或count(r.recruit_id)
来获取计数。
如果bin(refs)
列包含任何值,那么count
将无法为您提供正确的答案。在这种情况下,您需要使用sum
之类的Sum( bin(refs))
。
答案 2 :(得分:0)
SELECT ipb.*, COUNT(`r`.`recruit_id`) AS cid FROM `ipb`
INNER JOIN `r` ON `r`.`join_id` = ipb.`member_id`
GROUP BY ipb.`member_id`