gpt4 book ai didi

mysql - 从 MySQL 的数据库列中使用 LIMIT 进行 SELECT 查询

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:57 27 4
gpt4 key购买 nike

我有 2 个表:

user          messages
+---------+ +----------------+
|id|credit| |id|user_id| ... |
+---------+ +----------------+
|01| 05 | |01| 01 | ... |
|02| 01 | |02| 01 | ... |
|03| 00 | |03| 01 | ... |
+---------+ |04| 02 | ... |
|05| 02 | ... |
|06| 03 | ... |
+----------------+

我需要从 messages 中选择 n 条消息,其中 n=user.credit。我想执行如下查询的查询:

SELECT * 
FROM user u JOIN messages m ON u.id = m.user_id LIMIT u.credit
WHERE user in ...;

并且应该返回第 01、02、03、04 行而不是 05、06 行。

我知道我不能写 LIMIT u.credit 但想要这种行为,根据他们拥有的信用值限制为每个用户获取的消息数量(用户 01 限制5 个,用户 02,限制为 1,依此类推),我想一次获取所有消息,以避免必须为每个用户执行 COUNT 和 SELECT。

我正在使用 MySQL 和 InnoDB

最佳答案

这是一个纯 SQL 解决方案,不使用变量:

select user.*, messages.*
from user inner join messages
on user.id=messages.user_id
where (select count(*) from messages m
where m.user_id=user.id
and m.id<messages.id)<user.credit

Demo

关于mysql - 从 MySQL 的数据库列中使用 LIMIT 进行 SELECT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com