选择总时间计数外键存在于表中

发布于 2025-01-27 11:44:34 字数 1748 浏览 3 评论 0原文

我的表设置如下如下候选

名单

ID(primary键)property_id(外键)user_id
11002
21012
31034
4 41001
51003
61011

属性

ID(主键)account_id
1001
1012
102 3 103103
1034

然后,我有以下查询,

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,该返回每个property_id字段中出现在shortlist 表。 (或ID 属性表中的字段,以此上下文中更容易的人),

例如property_id 100出现3 times在入围表中。

因此,结果应该是

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

ShortListCount当前始终返回1

我如何才能更新我的shortlistCount别名以返回上述结果?

My table setup is as follows

Shortlist

id (primary key)property_id(foreign key)user_id
11002
21012
31034
41001
51003
61011

Property

id (primary key)account_id
1001
1012
1023
1034

I then have the following query

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

I want to add a count field alias as shortlistCount that returns the total number of times each property_id field appears in the shortlist table. (or id field in the property table, whichever is easier in this context)

For example, the property_id of 100 appears 3 times in the shortlist table.

So the result should be

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

However, shortlistCount currently always returns 1

How can I can update my shortlistCount alias to return the above result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难忘№最初的完美 2025-02-03 11:44:34

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

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;

To count the property_ids you can use a correlated subquery:

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文