简体   繁体   English

有没有办法从MySQL的子选择中获取字段=>值对?

[英]Is there a way to get field => value pairs from a subselect in MySQL?

I'm considering how to best implement an Audit Trail in an app, which is backed by MySQL. 我正在考虑如何最好地在MySQL支持的应用程序中实施审核跟踪。 A few systems access the same database and tables, so I thought triggers would be the best solution. 一些系统访问相同的数据库和表,因此我认为触发器将是最佳解决方案。

However, I don't want to manually write a trigger for every table, so I'm looking to automatically log the field name and data for each insert/delete. 但是,我不想为每个表手动编写触发器,因此我希望自动记录每个插入/删除的字段名称和数据。

Something like: 就像是:

INSERT INTO `audits` SET
    `table_name` = 'jobs',
    `table_key` = OLD.`id`,
    `changed_at` = NOW(),
    `notes` = (SELECT * FROM NEW);

However, the subselect will return a single row result set, which cannot be treated as string. 但是,子选择将返回单行结果集,该结果集不能视为字符串。 I want a function that will take that row and convert it to: 我想要一个函数来接受该行并将其转换为:

"id = 1, name = 'something', another_field = 'data'"

Or something like that. 或类似的东西。

Edit: The main point here is that I don't want to have to type in every field in every table. 编辑:这里的要点是我不想在每个表中的每个字段中键入。 There's over 120 tables, and some have > 100 fields. 有超过120个表格,其中一些具有> 100个字段。 If it's not possible in MySQL itself, I guess I'll write a little program to spin over each table and field and generate the SQL for me. 如果MySQL本身无法实现,我想我会写一个小程序来旋转每个表和字段并为我生成SQL。

SELECT  CONCAT('id = ', id, ', name = ''', name, ''', another_field = ''', data, '''')
FROM    NEW

only 只要

SELECT GROUP_CONCAT(col1) FROM yourtable 从您的表中选择GROUP_CONCAT(col1)

but this return all field by comma delimiter or other separator that you can declare. 但这会以逗号分隔符或您可以声明的其他分隔符返回所有字段。

link 链接

You can just concatenate the strings. 您可以串联字符串。

eg: 例如:

select concat("id = ", t.id, "name = ", t.name) from myTable t;

我最终写了一个PHP脚本来遍历每个相关表并为我构建触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM