Feature: Subquery for SELECT

Signed-off-by: Andrey Pyzhikov <5071@mail.ru>
This commit is contained in:
Andrey Pyzhikov 2022-02-24 13:22:49 +08:00
parent 2179c9584d
commit 1541d0665a
No known key found for this signature in database
GPG Key ID: BA61560FB9B7B817
5 changed files with 53 additions and 0 deletions

View File

@ -445,6 +445,22 @@ class BaseBuilder
return $this->maxMinAvgSum($select, $alias, 'COUNT');
}
/**
* Adds a subquery to the selection
*
* @return static
*/
public function selectSubquery(BaseBuilder $subquery, string $as)
{
if (! $this->isSubquery($subquery)) {
throw new DatabaseException('The BaseBuilder::selectSubquery method expects a BaseBuilder instance');
}
$this->QBSelect[] = $this->buildSubquery($subquery, true, $as);
return $this;
}
/**
* SELECT [MAX|MIN|AVG|SUM|COUNT]()
*

View File

@ -246,4 +246,17 @@ final class SelectTest extends CIUnitTestCase
$this->assertSame($expected, str_replace("\n", ' ', $builder->getCompiledSelect()));
}
public function testSelectSubquery()
{
$builder = new BaseBuilder('users', $this->db);
$subquery = new BaseBuilder('countries', $this->db);
$subquery->select('name')->where('id', 1);
$builder->select('name')->selectSubquery($subquery, 'country');
$expected = 'SELECT "name", (SELECT "name" FROM "countries" WHERE "id" = 1) AS "country" FROM "users"';
$this->assertSame($expected, str_replace("\n", ' ', $builder->getCompiledSelect()));
}
}

View File

@ -24,6 +24,7 @@ Enhancements
- See :ref:`content-security-policy` for details.
- New View Decorators allow modifying the generated HTML prior to caching.
- Added Subqueries in the FROM section. See :ref:`query-builder-from-subquery`.
- Added Subqueries in the SELECT section.
- Added Validation Strict Rules. See :ref:`validation-traditional-and-strict-rules`.
- Added new OCI8 driver for database.
- It can access Oracle Database and supports SQL and PL/SQL statements.

View File

@ -167,6 +167,13 @@ the resulting field.
.. literalinclude:: query_builder/014.php
:lines: 2-
**$builder->selectSubquery()**
Adds a subquery to the SELECT section.
.. literalinclude:: query_builder/098.php
:lines: 2-
From
====
@ -1066,6 +1073,15 @@ Class Reference
Adds a ``SELECT COUNT(field)`` clause to a query.
.. php:method:: selectSubquery(BaseBuilder $subquery, string $as)
:param string $subquery: Instance of BaseBuilder
:param string $as: Alias for the resulting value name
:returns: ``BaseBuilder`` instance (method chaining)
:rtype: ``BaseBuilder``
Adds a subquery to the selection
.. php:method:: distinct([$val = true])
:param bool $val: Desired value of the "distinct" flag

View File

@ -0,0 +1,7 @@
<?php
$subquery = $db->table('countries')->select('name')->where('id', 1);
$builder = $db->table('users')->select('name')->selectSubquery($subquery, 'country');
$query = $builder->get();
// Produces: SELECT `name`, (SELECT `name` FROM `countries` WHERE `id` = 1) AS `country` FROM `users`