MySQL query: Using UNION and getting row number as part of SELECT

房东的猫 提交于 2019-12-02 07:27:29

问题


I have a union query as follows:

(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
Everything works fine but I have two questions:
  1. How do I add a column to the entire result set that gives the row number
  2. Could I do this without using UNION e.g. an advanced join?

Thanks for your time MySQL gurus!


回答1:


I can't test it righ now but from what I found, following might work:

Reference: Row Number Variable

SQL Statement

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 


来源:https://stackoverflow.com/questions/6122440/mysql-query-using-union-and-getting-row-number-as-part-of-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!