【发布时间】:2015-09-28 06:57:15
【问题描述】:
我有什么
我有多个这样的表:
- tbl_hw_inventar(hw_id、主机名、hw_typ_idfs、hw_created_user_idfs 等...)
- tbl_hw_typ(hw_typ_id、hw_typ_title 等...)
- tbl_user(用户 ID、用户名等)
- tbl_hw_edited(hw_edited_id、hw_edited_client_idfs、hw_edited_date、hw_edited_user_idfs)
我需要什么
我想输出一个包含以下信息的表格:
hw_id | Hostname | created | last edited
12315 | client-01 | 2015-05-06 15:31:06 (username) | 2015-07-02 09:46:17 (username) |
问题
如您所见,我可以通过 外键 和 内连接 到“tbl_hw_typ”获得类似 hw_typ 的信息。对于“hw_created_user_idfs”的信息和获取 userid 的 username 的内部连接也是如此。
但是我怎样才能获得上次编辑、日期时间和用户名?
在我的表“tbl_hw_edited”中,我有这样的条目:
row id | hw_id | datetime | user_id
代码
到目前为止,我的 SQL 查询如下所示:
SELECT `tbl_hw_inventar`.*, `tbl_hw_typ`.`hw_typ_title`, `tbl_user`.`username`, `tbl_hw_edited`.`hw_edited_id`
FROM `tbl_hw_inventar`
INNER JOIN `tbl_hw_typ`
ON `tbl_hw_inventar`.`hw_typ_idfs` = `tbl_hw_typ`.`hw_typ_id`
INNER JOIN `tbl_user`
on `tbl_hw_inventar`.`hw_create_user_idfs` = `tbl_user`.`id`
JOIN (
SELECT MAX(`tbl_hw_edited`.`hw_edited_id`), `tbl_hw_edited`.`hw_edited_client_idfs`
FROM `tbl_hw_edited`
) `tbl_hw_edited` ON `tbl_hw_inventar`.`hw_id` = `tbl_hw_edited`.`hw_edited_client_idfs`
ORDER BY `tbl_hw_inventar`.`hw_id` ASC
那么如何导出信息呢?看起来我必须在我的查询中创建一个子查询。但我每次尝试都失败了。
感谢您的帮助
编辑
按照建议,我将为每个表格提供更多信息(表格数据):
-tbl_hw_inventar-
| hw_id | hw_hostname | hw_create_date | hw_create_user_idfs |
| 1 | client-01 | 2015-03-06 11:57:42 | 1 |
| 2 | client-02 | 2015-09-21 21:17:00 | 3 |
-tbl_hw_edited-
| hw_edited_id | hw_edited_client_idfs | hw_edited_date | hw_edited_user_idfs |
| 1 | 1 | 2015-09-24 17:30:22 | 1 |
| 2 | 2 | 2015-09-24 16:33:22 | 2 |
| 3 | 1 | 2015-09-24 23:30:22 | 2 |
| 4 | 2 | 2015-09-24 20:30:22 | 3 |
-tbl_user-
| id | username |
| 1 | ismaelw |
| 2 | skalb |
| 3 | yrumpel |
所以作为最终结果,我需要这样的输出:
| hw_id | hostname | created | edited |
| 1 | client-01 | 2015-03-06 11:57:42 (ismaelw) | 2015-09-24 23:30:22 (skalb) |
【问题讨论】:
-
如果每个表都有几行数据,回答你的问题会更容易。拥有样本数据可以消除一些猜测,并允许我们测试我们的建议。
-
你从哪里得到创建日期?
-
@Used_By_Already 我添加了一些关于我需要什么和一些表数据行的更多细节。
-
是的,得到了数据,谢谢,我看到你有创建日期,只需将它添加到你需要的选择子句中