如何检查关系是否存在 - 多对多关系

发布于 2024-12-07 19:59:48 字数 259 浏览 0 评论 0原文

我需要你的帮助来弄清楚如何进行查询。 我的想法是建立一个信用体系来奖励用户。 管理员输入积分的描述(例如,用户订阅了时事通讯,他发布了至少 10 条评论......)。 我有 3 个表:

  • 用户(id 和名称)、
  • 奖励(id 和描述)、
  • rewards_users(id_reward、id_user)。

我会拉出一个摘要 html 表,其行由用户名和 Y 或 N 组成,具体取决于用户和奖励之间是否存在关系。

I need your help to figure out how to make a query.
My idea was to build a credit system to reward users.
The administrator enters the description of credits (e.g., user is subscribed to the newsletter, he had post at least 10 comments...).
I have 3 tables:

  • users (id and name),
  • rewards (id and description),
  • rewards_users (id_reward, id_user).

I would pull out a summary html table whose rows are formed by the user's name and a Y or an N depending on whether there is a relationship between the user and the reward.

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

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

发布评论

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

评论(2

各自安好 2024-12-14 19:59:48

使用以下查询显示特定用户的所有奖励

SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded
FROM rewards r
LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = 1

,并将其用作子查询来获取用户详细信息,

例如:

SELECT u.user_id, u.user_name, ua.award, ua.awarded
FROM users u,
     (
     SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded
     FROM rewards r
     LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = u.user_id
     ) ua
WHERE u.userid=1

注意:未经测试。

use the following query to show all of the rewards for a specific user

SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded
FROM rewards r
LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = 1

and use it as a sub query to get the users details too

e.g:

SELECT u.user_id, u.user_name, ua.award, ua.awarded
FROM users u,
     (
     SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded
     FROM rewards r
     LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = u.user_id
     ) ua
WHERE u.userid=1

Note: not tested.

单挑你×的.吻 2024-12-14 19:59:48

在我看来,您需要在用户表和rewards_users表之间进行左连接,然后处理空rewards_id的实例:

select u.id as users_id,
u.name as users_name,
case when ur.rewards_id is null then 'N' else 'Y' end as hasRewards
from users u left join users_rewards ur
on u.id = ur.users_id;

Sounds to me like you need a LEFT JOIN between your users table and the rewards_users table and then to handle instances of null rewards_id:

select u.id as users_id,
u.name as users_name,
case when ur.rewards_id is null then 'N' else 'Y' end as hasRewards
from users u left join users_rewards ur
on u.id = ur.users_id;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文