yiisoft / yiisoft/db

QueryBuilder: union and order by not works

Open
#81 45 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

  • #709 by @terabytesoftw — closed without merging
Dominant language
PHP
Stars
216
Forks
51
Avg merge
3d 10h
Merged PRs (30d)
2

Description

I have:

$query1 = (new \yii\db\Query())
    ->select("id, category_id AS type, name")
    ->from('post')

$query2 = (new \yii\db\Query())
    ->select('id, type, name')
    ->from('user')
    ->orderBy('type');

$query1->union($query2);

This code generates the following SQL:

(SELECT `user`.`id`, `user`.`category_id` AS `type`, `user`.`name` FROM `post`) 
UNION
(SELECT `user`.`id`, `user`.`category_id`, `user`.`name`  FROM `post` ORDER BY `type`) 

The SQL above does not order correctly.
It's necessary remove the parentheses. Ex:

SELECT `user`.`id`, `user`.`category_id` AS `type`, `user`.`name` FROM `post`
UNION
SELECT `user`.`id`, `user`.`category_id`, `user`.`name`  FROM `post` ORDER BY `type`

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the QueryBuilder union and orderBy SQL-generation paths and reproduce the query shown in the issue. Compare the generated SQL with the expected unparenthesized UNION output; done means the ordering behavior matches that example.

Written by the indexing model from the issue text.

Assessment

Tech stack
php, sql
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.