Kolyunya
Kolyunya

Reputation: 6240

Yii2 construct a query with union and limit

I need to construct an SQL query containing two queries combined by UNION and limit a number of rows returned.

    $query = $queryOne
        ->union($queryTwo)
        ->limit($this->limit)
    ;

The problem is that the LIMIT clause is enclosed in parentheses with the first query. As a result of this the second query has no LIMIT clause.

I need to specify the LIMIT clause for the whole query not for a subquery.

Upvotes: 2

Views: 2991

Answers (1)

Kolyunya
Kolyunya

Reputation: 6240

You will need a third query to solve the problem somewhat elegantly:

    $query = (new Query)
        ->select('*')
        ->from([
            $queryOne->union($queryTwo),
        ])
        ->offset($offset)
        ->limit($limit)
    ;

Related.

Upvotes: 5

Related Questions