mysql - 使用@rownum :=@rownum+1 AS rownum 枚举 SQL 中的每条记录

标签 mysql sql

我在 MySQL 中有这个查询

SELECT 
@rownum:=@rownum+1 AS rownum,
notifications_posts.from_user AS source,
notifications_posts.on_post_id AS destination,
notifications_posts.in_group_id,
groups.group_name AS group_name,
notifications_posts.on_post_id AS other_record_id,
user_info.first_name,
user_info.last_name,
user_info.user_id,
notifications_posts.date,
posts.title AS 'title',
user_rights.right AS 'right',
'article' AS notification_type
FROM notifications_posts
INNER
    JOIN user_info
    ON notifications_posts.from_user = user_info.user_id
INNER
    JOIN posts
    ON posts.id = notifications_posts.on_post_id
INNER
    JOIN groups
    ON groups.group_id = notifications_posts.in_group_id
INNER
    JOIN user_rights
    ON user_rights.group_id = notifications_posts.in_group_id AND user_rights.user_id = user_info.user_id

我明白了

enter image description here

为什么我在 rownum 处得到 NULL

其次,我需要按该 id 对记录进行分组

GROUP BY rownum;

谁能帮帮我?

最佳答案

我认为最好只对结果进行排序(在 MySQL 中),然后在您的应用程序中添加行号。如果您坚持:

警告:任何以这种方式使用变量的查询都可能在未来版本的 MySQL 中被破坏。

SELECT 
    @rownum := @rownum+1 AS rownum,
    notifications_posts.from_user AS source,
    notifications_posts.on_post_id AS destination,
    notifications_posts.in_group_id,
    groups.group_name AS group_name,
    notifications_posts.on_post_id AS other_record_id,
    user_info.first_name,
    user_info.last_name,
    user_info.user_id,
    notifications_posts.date,
    posts.title AS 'title',
    user_rights.right AS 'right',
    'article' AS notification_type
FROM 
    (SELECT @rownum:=0) AS dummy                  -- initial value
CROSS 
    JOIN notifications_posts
INNER
    JOIN user_info
    ON notifications_posts.from_user = user_info.user_id
INNER
    JOIN posts
    ON posts.id = notifications_posts.on_post_id
INNER
    JOIN groups
    ON groups.group_id = notifications_posts.in_group_id
INNER
    JOIN user_rights
    ON user_rights.group_id = notifications_posts.in_group_id 
    AND user_rights.user_id = user_info.user_id 
ORDER BY                                         -- you need 
    whatever ;                                   -- ORDER BY clause

关于mysql - 使用@rownum :=@rownum+1 AS rownum 枚举 SQL 中的每条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12578938/

相关文章:

sql - Postgres 递增列中的空值

php - 如何在表格的所有列中进行搜索?

php - 如何导出/导入 utf8-general-ci 数据库?

MySQL 插入 CASE WHEN/THEN/ELSE

php - Codeigniter Join 弄乱了 'id' 字段

sql - 从表中选择特定行

php - SQL 查询转义 + codeigniter

mysql - 在 MySQL 中使用 SELECT 语法创建表

php - 在非对象上调用成员函数 escape_string()

SQLite 和多次写入