[英]Loop through SQL query using variable from another table
I have two tables file & users, I want to see the file info for each user for C:\\Users\\%USERNAME%\\Documents
我有两个表文件和用户,我想查看
C:\\Users\\%USERNAME%\\Documents
每个用户的文件信息
So eg this would get the info from 'example' documents:因此,例如这将从“示例”文档中获取信息:
SELECT *
FROM file
WHERE path LIKE 'C:\Users\example\Documents\%%';
But the username is coming from the users但是用户名来自用户
SELECT username FROM users;
returns返回
+--------------------+
| username |
+--------------------+
| Administrator |
| DefaultAccount |
| example |
| Guest |
| WDAGUtilityAccount |
| SYSTEM |
| LOCAL SERVICE |
| NETWORK SERVICE |
+--------------------+
Alternatively, there's:或者,有:
SELECT directory FROM users;
+---------------------------------------------+
| directory |
+---------------------------------------------+
| |
| |
| C:\Users\example |
| |
| |
| %systemroot%\system32\config\systemprofile |
| %systemroot%\ServiceProfiles\LocalService |
| %systemroot%\ServiceProfiles\NetworkService |
+---------------------------------------------+
Which provides the first part of the path, but still can't get to join 'Documents' to end of query and also run the file query.它提供了路径的第一部分,但仍然无法将“文档”加入到查询末尾并运行文件查询。
So, how do I loop through the each of the usernames.那么,我如何遍历每个用户名。
I've tried modifying but neither table can be modified我试过修改,但两个表都不能修改
This is a great opportunity to use a JOIN
query:这是使用
JOIN
查询的绝佳机会:
SELECT f.*
FROM file f JOIN users u
WHERE f.path LIKE 'C:\Users\' || u.username || '\Documents\%%'
When you run this query, osquery will first generate the list of users, then substitute the username into the path provided to the file
table.运行此查询时,osquery 将首先生成用户列表,然后将用户名替换为提供给
file
表的路径。
JOIN
is a really powerful way to combine the results of various tables, and it's well worth taking some time to experiment and learn how to use this power. JOIN
是一种非常强大的方法来组合各种表的结果,非常值得花一些时间来试验和学习如何使用这种能力。
Zach's answer is great, but there are times that a user's directory can be named differently than their respective username. Zach 的回答很好,但有时用户目录的命名可能与其各自的用户名不同。
Thankfully, we also have the directory
column in the users
table which returns a user's home directory.值得庆幸的是,我们在
users
表中还有directory
列,它返回用户的主目录。 Using this column will prevent directory/username mismatches from causing issues in your query output:使用此列将防止目录/用户名不匹配导致查询输出出现问题:
SELECT f.*
FROM file f JOIN users u
WHERE f.path LIKE u.directory || '\Documents\%%';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.