Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By slayerment on
I am trying to do a mysql union in Drupal 7 and I can't seem to get it right.
Here is what I want:
(
SELECT uid, nid, created
FROM {node}
)
UNION
(
SELECT uid, nid, created
FROM {comment}
)
ORDER BY created DESC
Here is what I have:
$query1 = db_select('node', 'n')
->fields('n', array('uid', 'nid', 'created'));
$query2 = db_select('comment', 'c')
->fields('c', array('uid', 'nid', 'created'));
$query1->union($query2, 'UNION ALL');
$result = $query1->orderBy('created', 'DESC')->execute();
The above code is giving me the following error:
PDOException: SQLSTATE[HY000]: General error: 1221 Incorrect usage of UNION and ORDER BY: SELECT n.uid AS uid, n.nid AS nid, n.created AS created FROM {node} n ORDER BY created DESC UNION ALL SELECT c.uid AS uid, c.nid AS nid, c.created AS created FROM {comment} c; Array ( ) in ...
Any help would be much appreciated.
Thanks!
Quinton
Comments
This bug has been reported
This bug has been reported (http://drupal.org/node/1145076) but there's no fix for it yet, judging by the comments and issue status it doesn't like it'll be fixed until Drupal 8.
The following works for
The following works for me:
orderBy added to last query object to sort union result. One would do the same to limit the result.
Neither OrderBy nor LIMITs
Neither OrderBy nor LIMITs are working for me with UNIONs.
The following works for me
The following works for me either.
Worked !
worked for me :) thanks !!
Thanks
This worked for me too...
Should not use "order by" before the union happens
You can see the query itself if you use the "dpq()" function from the devel module. (This can help you troubleshoot query problems in general.) The solution presented by @Reshma works properly:
http://drupal.stackexchange.com/questions/116391/how-to-add-union-with-p...
Essentially, you create a third query that acts as the union of the first two, and then you add your order-by's and etc. Hope that helps.
Rob Bailey
Thanks
Thanks, @Rob Bailey, This link helped a lot.