下午好,
我创建了一个存储函数来模拟" SHOW GRANTS FOR"的行为。 MySQL中的命令。脚本定义如下:
CREATE FUNCTION get_grants(p_user text, p_host text, p_type text, p_obj text)
RETURNS text
NOT DETERMINISTIC
READS SQL DATA
BEGIN
...
END;
如果我在select语句中使用该函数它正确执行。例如:
SELECT User as USER, Host as HOST,
'GLOBAL' as PRIV_TYPE, NULL as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'GLOBAL', '') as PRIVILEGES
FROM mysql.user
但是,当我使用 UNION 或 UNION ALL 语句连接2个用不同参数值调用函数的select语句时,如下所示:
SELECT User as USER, Host as HOST,
'GLOBAL' as PRIV_TYPE, NULL as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'GLOBAL', '') as PRIVILEGES
FROM mysql.user
UNION ALL
SELECT User as USER, Host as HOST,
'DB' as PRIV_TYPE, Db as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'DB', Db) as PRIVILEGES
FROM mysql.db
ORDER BY USER, HOST, DATABASE_NAME IS NULL, DATABASE_NAME;
我收到以下错误:#1222 - 使用的SELECT语句具有不同的列数。
有人能解释一下这里发生了什么,以及如何解决这个问题?
提前致谢。
答案 0 :(得分:0)
我认为导致这个问题的是UNION ALL。 通常如果使用UNION ALL,如果列数不同则无关紧要,但UNION必须相同。 因此,请尝试使用UNION ALL并将NULL作为DATABASE_NAME删除,或仅使用UNION并将NULL保留为DATABASE_NAME
SELECT User as USER, Host as HOST,
'GLOBAL' as PRIV_TYPE, NULL as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'GLOBAL', '') as PRIVILEGES
FROM mysql.user
UNION
SELECT User as USER, Host as HOST,
'DB' as PRIV_TYPE, Db as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'DB', Db) as PRIVILEGES
FROM mysql.db
ORDER BY USER, HOST, DATABASE_NAME IS NULL, DATABASE_NAME;
OR
SELECT User as USER, Host as HOST,
'GLOBAL' as PRIV_TYPE,
mydatabase.get_grants(User, Host, 'GLOBAL', '') as PRIVILEGES
FROM mysql.user
UNION ALL
SELECT User as USER, Host as HOST,
'DB' as PRIV_TYPE, Db as DATABASE_NAME,
mydatabase.get_grants(User, Host, 'DB', Db) as PRIVILEGES
FROM mysql.db
ORDER BY USER, HOST, DATABASE_NAME IS NULL, DATABASE_NAME;
答案 1 :(得分:0)
在几乎油炸我的大脑试图找到问题之后,事实证明实际问题与MySQL提供的错误消息没有任何关系(至少没有提供有关文档中此错误消息的描述)
在这种情况下,错误是在存储函数的实现中。在SELECT ... INTO命令中,我在INTO子句中的两个变量之间缺少“,”。选择的列数与INTO子句中的变量数相对应,问题解决了,我设法在上述查询中使用该函数,没有任何问题。
作为参考,有问题的查询是:
SELECT Select_priv, Insert_priv, Update_priv, Delete_priv,
Create_priv, Alter_priv, Index_priv, Drop_priv,
Create_tmp_table_priv, Create_view_priv, Show_view_priv,
Create_routine_priv, Alter_Routine_priv, Execute_priv,
Event_priv, Trigger_priv, Grant_priv, Lock_tables_priv,
References_priv
INTO v_select_priv, v_insert_priv, v_update_priv, v_delete_priv,
v_create_priv, v_alter_priv, v_index_priv, v_drop_priv,
v_tmptables_priv, v_createview_priv, v_showview_priv,
v_createroutine_priv, v_alterroutine_priv, v_execute_priv,
v_event_priv, v_trigger_priv, v_grant_priv, v_locktables_priv,
v_references_priv
FROM mysql.db
WHERE User = p_user
AND Host = p_host
AND Db = p_obj;