将不同的列值与其他表交叉

时间:2019-09-06 12:05:25

标签: mysql

PERMISSIONS表(query_1)中具有的'USER'的不同值中,我打算将信息与ACCESS_CONTROL表(query_2)中的查询值进行交叉,以了解每个信息需要多长时间具有访问权限的“ USER”尚未登录。

我打算通过“ USER”键字段将query_1与query_1交叉。 怎么可能?

查询_1:

SELECT DISTINCT(`USER`) FROM `PERMISSIONS`;

query_2:

SELECT 

`USER`, 
MAX(`REGISTRY_DATE`) AS MAX_REGISTRY_DATE, 
DATEDIFF(CURDATE(),MAX(`REGISTRY_DATE`)) AS DIFFERENCE_IN_DAYS

FROM `ACCESS_CONTROL` 

WHERE STATUS = 'Access Allowed' 

GROUP BY `USER` ORDER BY DIFFERENCE_IN_DAYS DESC;

预期结果:https://imgur.com/a/f5KQXWC

1 个答案:

答案 0 :(得分:1)

在第一个查询和第二个查询的左连接处:

select
  u.user, 
  coalesce(a.registry_date, 'never') max_registry_date,
  coalesce(a.difference_in_days, 'never') difference_in_days
from (
  select distinct user
  from permissions
) u left join (
  select user, max(registry_date) registry_date, 
  datediff(curdate(), max(registry_date)) difference_in_days
  from access_control 
  where `status` = 'Access Allowed' 
  group by user 
) a on a.user = u.user 

请参见demo
结果:

| user     | max_registry_date | difference_in_days |
| -------- | ----------------- | ------------------ |
| john     | 2019-09-06        | 0                  |
| susan    | 2019-09-01        | 5                  |
| mike     | 2019-08-06        | 31                 |
| anderson | never             | never              |