MySQL查询:使用UNION并将行号作为SELECT的一部分
作者:互联网
我有一个联合查询,如下所示:
(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专家!
解决方法:
我现在无法对其进行严格测试,但是从我发现的结果来看,以下方法可能有效:
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 来源: https://codeday.me/bug/20191013/1906174.html