SQL-动态权重查询

发布于 2024-10-30 19:03:10 字数 670 浏览 0 评论 0原文

我有一个数据库,其中的用户拥有项目列表。
简单的设计:

用户:

UserStuff |用户 ID

项目列表:

itemID | UserID

每个用户都有一个项目列表。一个Item可以属于多个用户(相同的itemID,不同的userID)。

现在我想动态地为项目赋予权重(在运行时计算,而不是可以存储在数据库中的常量),然后根据其项目选择权重最高的用户。

我可以在 SQL 查询中赋予项目权重,然后进行计算吗?

我试图避免循环数据库并计算用户的权重。

编辑:

示例:

UserStuff | 用户ID
废话1 | 1
废话2 | 2

项目ID | 用户ID
1 | 1
1 | 2
2 | 1
3 | 1
4 | 2
5 | 1

权重:
项目 ID = 1 = 15 itemID = 2 = 10

UserID1 总重量 = 25
UserID2总权重=10

I have a database with users that have a list of items.
Simple design:

Users:

UserStuff | UserID

ItemsList:

itemID | UserID

Each user has a list of items. An Item can belong to many users (same itemID, different userID).

Now I want to give weights to the items dynamically (calculated at runtime, not something constant that can be stored in the database) and then Select the users with the highest weights according to their Items.

Can I give the weight to the items in an SQL query, and then do the calculation ?

I'm trying to avoid looping through the database and calculating the users' weights.

Edit:

example:

UserStuff | UserID
blah1 | 1
blah2 | 2

itemID | UserID
1 | 1
1 | 2
2 | 1
3 | 1
4 | 2
5 | 1

wieghts:
itemId = 1 = 15
itemID = 2 = 10

UserID1 total weight = 25
UserID2 total weight = 10

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

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

发布评论

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

评论(1

没企图 2024-11-06 19:03:10

使用您的动态值创建临时权重表:

CREATE TEMPORARY TABLE weights(item_id integer, weight integer);
CREATE TABLE
INSERT INTO weights VALUES (1, 10);  -- Inserting weights
INSERT 0 1
INSERT INTO weights VALUES (2, 1);   -- Inserting weights
INSERT 0 1
...

创建视图以将项目映射到权重:

CREATE TEMPORARY VIEW items_weights AS 
       SELECT il.itemID, il.UserID, w.weight FROM
              ItemsList il JOIN weights w 
              ON il.itemID=w.item_id;

选择权重最高的用户:

SELECT UserId, COUNT(weight) FROM items_weights
       GROUP BY UserId ORDER BY COUNT(weight) DESC;

Create a temporary table of weights, with your dynamic values:

CREATE TEMPORARY TABLE weights(item_id integer, weight integer);
CREATE TABLE
INSERT INTO weights VALUES (1, 10);  -- Inserting weights
INSERT 0 1
INSERT INTO weights VALUES (2, 1);   -- Inserting weights
INSERT 0 1
...

Create a view to map items to weights:

CREATE TEMPORARY VIEW items_weights AS 
       SELECT il.itemID, il.UserID, w.weight FROM
              ItemsList il JOIN weights w 
              ON il.itemID=w.item_id;

Select the highest-weighted users:

SELECT UserId, COUNT(weight) FROM items_weights
       GROUP BY UserId ORDER BY COUNT(weight) DESC;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文