如何在MySQL中为每个用户最多选择3个项目? [英] How to select maximum 3 items per users in MySQL?

查看:138
本文介绍了如何在MySQL中为每个用户最多选择3个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行一个网站,用户可以发布商品(例如图片)。这些项目存储在MySQL数据库中。

I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database.

我想查询最后10个已发布项目,但最多3个项目的约束可以来自任何单个用户。

I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user.

这是最好的方法是什么?我的首选解决方案是对SQL查询请求最后十个项目的约束。但是,如何设置数据库设计的想法是非常受欢迎的。

What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome.

提前感谢!

/ p>

BR

推荐答案

使用相关子查询很容易:

It's pretty easy with a correlated sub-query:

SELECT `img`.`id` , `img`.`userid`
FROM `img`
WHERE 3 > (
SELECT count( * )
FROM `img` AS `img1`
WHERE `img`.`userid` = `img1`.`userid`
AND `img`.`id` > `img1`.`id` )
ORDER BY `img`.`id` DESC
LIMIT 10 

查询假设较大的 id 表示稍后添加

The query assumes that larger id means added later

相关子查询是一个强大的工具! : - )

Correlated sub-queries are a powerful tool! :-)

这篇关于如何在MySQL中为每个用户最多选择3个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆