title: MYSQL: Error joining 2 select statements that include a stored function
body: <p>Good Afternoon,</p>
  
  <p>I created a stored function to emulate the behavior of the "SHOW GRANTS FOR" command in MySQL. The script definition is as follows:</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>If I use the function in a select statement It is executed correctly. For example:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>However, when I use a <strong>UNION</strong> or <strong>UNION ALL</strong> statement to join 2 select statements that call the function with different parameter values, like this:</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>I get the following error: <strong>#1222 - The used SELECT statements have a different number of columns</strong>.</p>
  
  <p>Can anyone explain what's going on here and how to resolve this issue?</p>
  
  <p>Thanks in advance.</p>