ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

MySQL查询:使用UNION并将行号作为SELECT的一部分

2019-10-13 07:15:07  阅读:355  来源: 互联网

标签:row-number mysql join union



我有一个联合查询,如下所示:

(SELECT t.id, t.name, c.company AS owner, t.creation_date AS date, t.notes
 FROM tool t, client c
 WHERE t.id_customer = '15' AND t.trash_flag = '1')
  UNION
(SELECT f.id, f.name, CONCAT(m.first_name, ' ', m.last_name) AS owner, f.date, f.notes
 FROM file f, meta m
 WHERE ((f.acl = 0) OR (f.acl = 1 AND '1' = TRUE) OR (f.acl = 2 AND f.id = '7')) AND f.id = '15' AND f.trash_flag = '1' AND m.user_id = f.id_user) 
 ORDER BY 'name' 'ASC' LIMIT 0,20

一切正常,但我有两个问题:

>如何在整个结果集中添加一列以提供行号
>我可以不使用UNION来执行此操作吗?高级加入?

感谢您的宝贵时间MySQL专家!

解决方法:

我现在无法对其进行严格测试,但是从我发现的结果来看,以下方法可能有效:

参考:Row Number Variable

SQL语句

SELECT  @rownum := @rownum + 1 rownum
        , t.*
FROM    (
            (SELECT t.id
                    , t.name
                    , c.company AS owner
                    , t.creation_date AS date
                    , t.notes 
            FROM    tool t
                    , client c 
            WHERE   t.id_customer = '15' 
                    AND t.trash_flag = '1' 
            ) UNION (
            SELECT  f.id
                    , f.name
                    , CONCAT(m.first_name, ' ', m.last_name) AS owner
                    , f.date
                    , f.notes 
            FROM    file f
                    , meta m 
            WHERE   ((f.acl = 0) OR (f.acl = 1 AND '1' = TRUE) OR (f.acl = 2 AND f.id = '7')) AND f.id = '15' AND f.trash_flag = '1' AND m.user_id = f.id_user) 
            )
        ) t
        , (SELECT @rownum := 0) r
ORDER BY 
        'name' ASC
LIMIT   0, 20 


标签:row-number,mysql,join,union

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有