Select 外键在 table 中存在的总次数计数

Select count for total times foreign key exists in table with join

我的table设置如下

候选名单

id (primary key) property_id(foreign key) user_id
1 100 2
2 101 2
3 103 4
4 100 1
5 100 3
6 101 1

属性

id (primary key) account_id
100 1
101 2
102 3
103 4

然后我有以下查询

SELECT DISTINCT `s`.`user_id`, `s`.`property_id`, `p`.`id`, `p`.`account_number`, COUNT(`s`.`property_id`) as `shortlistCount` 
FROM `shortlist` `s` 
INNER JOIN `property` `p` ON s.`property_id` = p.`id` 
WHERE s.`user_id` = "2" 
GROUP BY s.`property_id` 
LIMIT 10

我想添加一个计数字段别名 shortlistCount,returns 每个 property_id 字段出现在 shortlist [=50= 中的总次数]. (或 property table 中的 id 字段,以在此上下文中更容易的为准)

例如100property_id在入围名单table中出现3

所以结果应该是

| user_id | property_id | id  | account_number | shortlistCount |
|---------|-------------|-----|----------------|----------------|
| 2       | 100         | 100 | 1              | 3              |
| 2       | 101         | 101 | 2              | 2              |

但是,shortlistCount 目前总是 returns 1

如何将我的 shortlistCount 别名更新为 return 以上结果?

要计算 property_id 的数量,您可以使用相关子查询:

SELECT s.user_id, s.property_id, p.id, p.account_number, 
 (select Count(*) from Shortlist s2 where s2.property_id = s.property_id) shortlistCount 
FROM shortlist s 
JOIN property p ON s.property_id = p.id 
WHERE s.user_id = 2
LIMIT 10;