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

标签 mysql sql database

我有 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/

相关文章:

php - 登录php脚本不允许登录

MySql错误: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

mysql - 仅当新值最高时才插入

mysql - 在一个表中使用联接

php - MYSQL意外插入多行

php - 数据库总是网络数据存储的解决方案吗?

Django:数据库中的默认值,而不仅仅是 ORM

c# - Windows Phone 8.1 本地数据库

php - 如何从其他国家语言的数据库中获取日期?

c# - SQL CE 3.5 部署问题,涉及 C# 和 C++ 之间的互操作