我们如何通过限制相同列的数量 MySql 从 table 中获取数据

How we can get the data from the table by limiting the number of identical columns MySql

昨天我尝试使用 'user_id' 作为限制每个用户的数据量的标准从我的数据库 table 检索数据。

我尝试从 table https://prnt.sc/p53zhp in format like this https://prnt.sc/p541wk 获取数据并限制 user_id 的输出记录数,其中限制为 2 (count(user_id) <= 2),但我不明白该怎么做。我可以使用哪种 sql 请求来获取此数据?

我不明白你的问题是 Transact-SQL 还是你的代码。

在SQL中你可以用"LIMIT"限制记录:https://www.w3schools.com/sql/sql_top.asp

在代码中,您可以使用条件 IF。

假设您的 RDBMS,这里有一个解决方案哟 select 每个用户只有前 2 条记录。您可以在子查询中使用 ROW_NUMBER() 在具有相同 user_id 的记录组中按 id 对记录进行排名,并在外部查询中过滤掉不相关的记录,例如:

SELECT *
FROM (
    SELECT
        t.*,
        ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY id)
    FROM mytable
) x WHERE rn <= 2

在 MySQL 的早期版本中,您可以使用 self-LEFT JOIN 和 table 并使用 GROUP BYHAVING COUNT(...) < 2 将结果限制为第一个每组两条记录:

SELECT 
    t.id, 
    t.user_id, 
    t.vip, 
    t.title,
    t.description,
    t.data 
FROM mytable t
LEFT JOIN mytable t1 ON t1.user_id = t.user_id AND t1.id > t.id
GROUP BY
    t.id, 
    t.user_id, 
    t.vip, 
    t.title,
    t.description,
    t.data 
HAVING COUNT(t1.id) < 2