Pregunta

I have a little problem regarding MySQL

I'm trying to make a UNION of two tables like so:

SELECT `user_id`, `post_id`, `requested_on`
   FROM `a` 
      WHERE `status` != 'cancelled' 

UNION 

SELECT `user_id`, `post_id`, `time` as requested_on 
   FROM `b` 
      WHERE `type` = 'ADD' 

This query is executed in Showing rows 0 - 29 (36684 total, Query took 0.0147 sec)

but when I do

SELECT * FROM (
   SELECT `user_id`, `post_id`, `requested_on`
      FROM `a` 
         WHERE `status` != 'cancelled' 

   UNION 

   SELECT `user_id`, `post_id`, `time` as requested_on 
      FROM `b` 
         WHERE `type` = 'ADD' 
) tbl1

MySQL dies.

The reason why I want to do this is to GROUP BY user_id, post_id

Any ideas why this happens / any workarounds?

later-edit:

This is the SQL Fiddle:

http://sqlfiddle.com/#!2/c7f82d/2

The final query is there, which executes in:

Record Count: 10; Execution Time: 574ms

574ms for 10 records in my point of view is gigantic.

¿Fue útil?

Solución

I found what the problem was from.

It was the fact that I was running the queries in PHPMyAdmin and when I did a SELECT UNION SELECT everything was good but when I did SELECT * FROM (SELECT UNION SELECT) the pagination system from PHPMyAdmin failed, and PHPMyAdmin was trying to output to my browser a over 30k rows table, that's why the SQL Request hang. :(

Otros consejos

It is not clear what the question:

SELECT * FROM (
   SELECT user_id, post_id, requested_on
      FROM a
         WHERE status != cancelled
   UNION 
   SELECT user_id, post_id, time as requested_on 
      FROM b 
         WHERE type = ADD 
) tbl1 GROUP BY user_id, post_id

means. Assume you have:

A, x, t1 A, x, t2

would you like the row with t1 or t2? If that does not matter lets apply an aggregate function such as MIN:

SELECT user_id, post_id, MIN(requested_on) FROM (
   SELECT user_id, post_id, requested_on
   FROM a
   WHERE status <> cancelled
   UNION 
   SELECT user_id, post_id, time as requested_on 
   FROM b 
   WHERE type = ADD 
) tbl1 
GROUP BY user_id, post_id

MySQL usually doesn't handle derived tables like this very well, is there any other predicate that you can apply to the parts in the union?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top