| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304 |
- <sect1 id="zend.db.select">
- <title>Zend_Db_Select</title>
- <sect2 id="zend.db.select.introduction">
- <title>Visão Geral do Objeto Select</title>
- <para>
- O objeto Zend_Db_Select representa um comando de consulta SQL <code>SELECT</code>.
- A classe possui métodos para a adição de partes individuais em uma query. Você
- pode especificar algumas partes da consulta usando métodos PHP e estruturas de
- dados, e a classe se encarrega de formar a sintaxe SQL correta para você. Depois
- da construção de uma consulta, você pode executá-la como se você houvesse a escrito
- em uma string.
- </para>
- <para>
- As vantagens oferecidas pelo Zend_Db_Select incluem:
- </para>
- <itemizedlist>
- <listitem>
- <para>
- Métodos orientados a objetos para especificação de consultas SQL
- de maneira "piece-by-piece" (aos pedaços ou em partes);
- </para>
- </listitem>
- <listitem>
- <para>
- Abstração de independência de base de dados de algumas partes
- da consulta SQL;
- </para>
- </listitem>
- <listitem>
- <para>
- Colocação automática de aspas nos identificadores de metadados na maioria
- dos casos, para dar suporte aos identificadores que contém palavras SQL reservadas
- e caracteres especiais;
- </para>
- </listitem>
- <listitem>
- <para>
- Colocação automática de aspas nos identificadores e valores, para ajudar
- na redução de ataques por "SQL injection".
- </para>
- </listitem>
- </itemizedlist>
- <para>
- A utilização de Zend_Db_Select não é obrigatória. Para consultas SELECT
- muito simples, normalmente é mais fácil escrever toda a consulta SQL
- em uma string e executá-la usando métodos da classe Adapter, como o
- <code>query()</code> ou <code>fetchAll()</code>. O uso de Zend_Db_Select
- é muito útil quando você precisa montar uma consulta SELECT usando "procedures"
- (através de procedimentos), ou quando você precisa montar a consulta baseando-se
- na lógica condicional da sua aplicação.
- </para>
- </sect2>
- <sect2 id="zend.db.select.creating">
- <title>Criando um Objeto Select</title>
- <para>
- Você pode criar uma instância de um objeto Zend_Db_Select
- usando o método <code>select()</code> de um objeto Zend_Db_Adapter_Abstract.
- </para>
- <example id="zend.db.select.creating.example-db">
- <title>Exemplo do método select() do adaptador para bases de dados</title>
- <programlisting role="php"><![CDATA[<?php
- $db = Zend_Db::factory( ...options... );
- $select = $db->select();]]></programlisting>
- </example>
- <para>
- Outra forma de criar um objeto Zend_Db_Select é com o
- construtor dele, especificando o adaptador como parâmetro.
- </para>
- <example id="zend.db.select.creating.example-new">
- <title>Examplo da criação de um novo objeto Select</title>
- <programlisting role="php"><![CDATA[<?php
- $db = Zend_Db::factory( ...options... );
- $select = new Zend_Db_Select($db);]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.db.select.building">
- <title>Construindo Consultas Select</title>
- <para>
- Ao contruir um consulta, você pode adicionar cláusulas uma por uma.
- Existe um método diferente para cada cláusula no objeto.
- </para>
- <example id="zend.db.select.building.example">
- <title>Exemplo do uso de métodos para adicionar cláusulas</title>
- <programlisting role="php"><![CDATA[<?php
- // Create the Zend_Db_Select object
- $select = $db->select();
- // Add a FROM clause
- $select->from( ...specify table and columns... )
- // Add a WHERE clause
- $select->where( ...specify search criteria... )
- // Add an ORDER BY clause
- $select->order( ...specify sorting criteria... );]]></programlisting>
- </example>
- <para>
- Você também pode usar a maior parte dos métodos do objeto Zend_Db_Select
- com uma interface "fluent" conveniente. Uma interface "fluent" significa que cada
- método retorna uma referência para o objeto no qual foi chamado, então você pode
- imediatamente chamar outro método.
- </para>
- <example id="zend.db.select.building.example-fluent">
- <title>Examplo de uso da interface "fluent"</title>
- <programlisting role="php"><![CDATA[<?php
- $select = $db->select()
- ->from( ...specify table and columns... )
- ->where( ...specify search criteria... )
- ->order( ...specify sorting criteria... );]]></programlisting>
- </example>
- <para>
- Os exemplos nesta seção mostram o uso da interface "fluent",
- mas você pode usar a interface "non-fluent" em todos os casos.
- É freqüentemente necessário usar a interface "non-fluent" quando, por exemplo,
- sua aplicação precisa executar alguma lógica antes de adicionar uma cláusula
- a uma consulta.
- </para>
- <sect3 id="zend.db.select.building.from">
- <title>Adicionando uma cláusula FROM</title>
- <para>
- Especifique a tabela para esta consulta usando o método <code>from()</code>.
- Você pode especificar o nome da tabela como uma simples string.
- Zend_Db_Select coloca o entre aspas o nome da tabela, então, você pode
- usar caracteres especiais.
- </para>
- <example id="zend.db.select.building.from.example">
- <title>Example of the from() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT *
- // FROM "products"
- $select = $db->select()
- ->from( 'products' );]]></programlisting>
- </example>
- <para>
- You can also specify the correlation name (sometimes called the
- "table alias") for a table. Instead of a simple string, use an
- associative array mapping the correlation name to the table
- name. In other clauses of the SQL query, use this correlation
- name. If your query joins more than one table, Zend_Db_Select
- generates unique correlation names based on the table names,
- for any tables for which you don't specify the correlation name.
- </para>
- <example id="zend.db.select.building.from.example-cname">
- <title>Example of specifying a table correlation name</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p.*
- // FROM "products" AS p
- $select = $db->select()
- ->from( array('p' => 'products') );]]></programlisting>
- </example>
- <para>
- Algumas marcas de RDBMS dão suporte a um especificador de schema
- para uma tabela. Você pode especificar o nome a tabela como
- "<code>schemaName.tableName</code>", onde Zend_Db_Select coloca entre aspas
- cada uma das partes individualmente, ou então você deve especificar o nome
- do schema separadamente. Um nome de schema especificado no nome da tabela
- precede um schema fornecido separadamente se eventualmente ambos forem
- informados.
- </para>
- <example id="zend.db.select.building.from.example-schema">
- <title>Exemplo de especificação de nome de schema</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT *
- // FROM "myschema"."products"
- $select = $db->select()
- ->from( 'myschema.products' );
- // or
- $select = $db->select()
- ->from('products', '*', 'myschema');]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.columns">
- <title>Adicionando Colunas</title>
- <para>
- No segundo argumento do método <code>from()</code> ,
- você pode especificaras colunas a serem selecionadas da
- respectiva tabela. Se você não especificar nenhuma coluna,
- o valor padrão é "<code>*</code>", o caracter curinga para "todas as colunas".
- </para>
- <para>
- Você pode listar as colunas em um simples array de strings, ou como
- um mapeamento associativo do alias da coluna para nome da coluna.
- Se você só tiver uma coluna para consultar, e não precisar indicar um
- alias, você pode listá-la em uma string simples ao invés de um array.
- </para>
- <para>
- Se você passar um array vazio como o argumento de colunas, nenhuma
- coluna da respectiva tabela será incluída no result set.
- Veja um exemplo de <link linkend="zend.db.select.building.join.example-no-columns">código</link> sob a seção do método <code>join()</code>.
- </para>
- <para>
- Você pode especificar o nome da coluna como
- "<code>correlationName.columnName</code>".
- Zend_Db_Select os coloca entre aspas individualmente.
- Caso você não especifique o nome da correlação para uma coluna,
- é usado o nome da correlação da tabela indicada no método<code>from()</code>.
- </para>
- <example id="zend.db.select.building.columns.example">
- <title>Examples of specifying columns</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'product_name'));
- // Build the same query, specifying correlation names:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('p.product_id', 'p.product_name'));
- // Build this query with an alias for one column:
- // SELECT p."product_id" AS prodno, p."product_name"
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('prodno' => 'product_id', 'product_name'));]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.columns-expr">
- <title>Adicionando Colunas de Expressões</title>
- <para>
- Algumas vezes as colunas de uma consulta SQL são expressões, e não
- simplesmente o nome de uma couna da tabela. Expressões não devem usar
- nomes de correlação ou aspas. Se a string da coluna possuir parênteses,
- Zend_Db_Select a reconhecerá como uma expressão.
- </para>
- <para>
- Você também pode criar um objeto do tipo Zend_Db_Expr explicitamente,
- para prevenir que uma string seja tratada como um nome de coluna.
- Zend_Db_Expr é uma classe diminuta que contém uma única string.
- Zend_Db_Select reconhece obtejos do tipo Zend_Db_Expr e os converte
- novamente para strings, mas não efetua qualquer alteração como a
- colocação de aspas ou nomes de correlação.
- </para>
- <note>
- <para>
- O uso de Zend_Db_Expr para nomes de colunas não é necessário se as
- expressões contiverem parênteses; Zend_Db_Select reconhece os parênteses
- e trata a string como uma expresão, ignorando a colocação de aspas e de
- nomes de correlação.
- </para>
- </note>
- <example id="zend.db.select.building.columns-expr.example">
- <title>Exemplos de especificação de colunas contendo expressões</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", LOWER(product_name)
- // FROM "products" AS p
- // An expression with parentheses implicitly becomes
- // a Zend_Db_Expr.
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'LOWER(product_name)'));
- // Build this query:
- // SELECT p."product_id", (p.cost * 1.08) AS cost_plus_tax
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'cost_plus_tax' => '(p.cost * 1.08)'));
- // Build this query using Zend_Db_Expr explicitly:
- // SELECT p."product_id", p.cost * 1.08 AS cost_plus_tax
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'cost_plus_tax' => new Zend_Db_Expr('p.cost * 1.08')));]]></programlisting>
- </example>
- <para>
- Nos casos acima, Zend_Db_Select não altera a string
- para colocar os nomes de correlação ou aspas. Se as
- mudanças forem necessárias para evitar alguma ambiguidade,
- você deve fazê-las manualmente na string.
- </para>
- <para>
- Se os nomes das colunas são palavras-chave SQL ou possuem
- caracteres especiais, você deve usar o método <code>quoteIdentifier()</code>
- da classe Adapter, e interpolar o resultado na string. O método
- <code>quoteIdentifier()</code> usa aspas no SQL para delimitar o identificador,
- o que deixa claro que ele é um identificador de uma tabela ou coluna e não
- parte da síntaxe SQL.
- </para>
- <para>
- Seu código fica mais independente de base de dados se você
- usar o método <code>quoteIdentifier()</code> ao invés de digitar
- as aspas nas strings porque algumas marcas de SGBD Relacionais usam
- símbolos fora do padrão para referenciar identificadores.
- O método <code>quoteIdentifier()</code> é projetado para usar
- os símbolos de referência apropriados de acordo com o tipo de adaptador.
- O método <code>quoteIdentifier()</code> também ignora qualquer
- caracter de referência que aparecer no nome de um identificador.
- </para>
- <example id="zend.db.select.building.columns-quoteid.example">
- <title>Examples of quoting columns in an expression</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query, quoting a special column name "from" in the expression:
- // SELECT p."from" + 10 AS origin
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('origin' => '(p.' . $db->quoteIdentifier('from') . ' + 10)'));]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.join">
- <title>Adding Another Table to the Query with JOIN</title>
- <para>
- Many useful queries involve using a <code>JOIN</code>
- to combine rows from multiple tables. You can add
- tables to a Zend_Db_Select query using the
- <code>join()</code> method. Using this method is
- similar to the <code>from()</code> method, except
- you can also specify a join condition in most cases.
- </para>
- <example id="zend.db.select.building.join.example">
- <title>Example of the join() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", p."product_name", l.*
- // FROM "products" AS p JOIN "line_items" AS l
- // ON p.product_id = l.product_id
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'product_name'))
- ->join(array('l' => 'line_items'),
- 'p.product_id = l.product_id');]]></programlisting>
- </example>
- <para>
- The second argument to <code>join()</code> is a string
- that is the join condition. This is an expression that
- declares the criteria by which rows in one table match
- rows in the the other table. You can use correlation
- names in this expression.
- </para>
- <note>
- <para>
- No quoting is applied to the expression you specify
- for the join condition; if you have column names that need
- to be quoted, you must use <code>quoteIdentifier()</code>
- as you form the string for the join condition.
- </para>
- </note>
- <para>
- The third argument to <code>join()</code> is an array
- of column names, like that used in the <code>from()</code>
- method. It defaults to "<code>*</code>", supports correlation
- names, expressions, and Zend_Db_Expr in the same way as the
- array of column names in the <code>from()</code> method.
- </para>
- <para>
- To select no columns from a table, use an empty array for
- the list of columns. This usage works in the
- <code>from()</code> method too, but typically you want
- some columns from the primary table in your queries,
- whereas you might want no columns from a joined table.
- </para>
- <example id="zend.db.select.building.join.example-no-columns">
- <title>Example of specifying no columns</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p JOIN "line_items" AS l
- // ON p.product_id = l.product_id
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id', 'product_name'))
- ->join(array('l' => 'line_items'),
- 'p.product_id = l.product_id',
- array() ); // empty list of columns]]></programlisting>
- <para>
- Note the empty <code>array()</code> in the above example
- in place of a list of columns from the joined table.
- </para>
- </example>
- <para>
- SQL has several types of joins.
- See the list below for the methods to support
- different join types in Zend_Db_Select.
- </para>
- <itemizedlist>
- <listitem>
- <para>
- <command>INNER JOIN</command> with the
- <code>join(table, join, [columns])</code>
- or <code>joinInner(table, join, [columns])</code> methods.
- </para>
- <para>
- This may be the most common type of join. Rows from
- each table are compared using the join condition you
- specify. The result set includes only the rows that
- satisfy the join condition. The result set can be
- empty if no rows satisfy this condition.
- </para>
- <para>
- All RDBMS brands support this join type.
- </para>
- </listitem>
- <listitem>
- <para>
- <command>LEFT JOIN</command> with the
- <code>joinLeft(table, condition, [columns])</code> method.
- </para>
- <para>
- All rows from the left operand table are included,
- matching rows from the right operand table included,
- and the columns from the right operand table are filled
- with NULLs if no row exists matching the left table.
- </para>
- <para>
- All RDBMS brands support this join type.
- </para>
- </listitem>
- <listitem>
- <para>
- <command>RIGHT JOIN</command> with the
- <code>joinRight(table, condition, [columns])</code> method.
- </para>
- <para>
- Right outer join is the complement of left outer join.
- All rows from the right operand table are included,
- matching rows from the left operand table included,
- and the columns from the left operand table are filled
- with NULLs if no row exists matching the right table.
- </para>
- <para>
- Some RDBMS brands don't support this join type, but
- in general any right join can be represented as a left
- join by reversing the order of the tables.
- </para>
- </listitem>
- <listitem>
- <para>
- <command>FULL JOIN</command> with the
- <code>joinFull(table, condition, [columns])</code> method.
- </para>
- <para>
- A full outer join is like combining a left outer join
- and a right outer join. All rows from both tables are
- included, paired with each other on the same row of the
- result set if they satisfy the join condition, and
- otherwise paired with NULLs in place of columns from the
- other table.
- </para>
- <para>
- Some RDBMS brands don't support this join type.
- </para>
- </listitem>
- <listitem>
- <para>
- <command>CROSS JOIN</command> with the
- <code>joinCross(table, [columns])</code> method.
- </para>
- <para>
- A cross join is a Cartesian product.
- Every row in the first table is matched to every
- row in the second table. Therefore the number of
- rows in the result set is equal to the product of
- the number of rows in each table. You can filter
- the result set using conditions in a WHERE clause;
- in this way a cross join is similar to the old SQL-89
- join syntax.
- </para>
- <para>
- The <code>joinCross()</code> method has no parameter
- to specify the join condition.
- Some RDBMS brands don't support this join type.
- </para>
- </listitem>
- <listitem>
- <para>
- <command>NATURAL JOIN</command> with the
- <code>joinNatural(table, [columns])</code> method.
- </para>
- <para>
- A natural join compares any column(s) that appear with
- the same name in both tables. The comparison is
- equality of all the column(s); comparing the columns
- using inequality is not a natural join.
- Only natural inner joins are supported by this API,
- even though SQL permits natural outer joins as well.
- </para>
- <para>
- The <code>joinNatural()</code> method has no parameter
- to specify the join condition.
- </para>
- </listitem>
- </itemizedlist>
- </sect3>
- <sect3 id="zend.db.select.building.where">
- <title>Adding a WHERE Clause</title>
- <para>
- You can specify criteria for restricting rows of the result set
- using the <code>where()</code> method. The first argument of
- this method is a SQL expression, and this expression is used
- in a SQL <code>WHERE</code> clause in the query.
- </para>
- <example id="zend.db.select.building.where.example">
- <title>Example of the where() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT product_id, product_name, price
- // FROM "products"
- // WHERE price > 100.00
- $select = $db->select()
- ->from(
- 'products',
- array('product_id', 'product_name', 'price'))
- ->where('price > 100.00');]]></programlisting>
- </example>
- <note>
- <para>
- No quoting is applied to expressions given to the
- <code>where()</code> or <code>orWhere()</code> methods.
- If you have column names that need to be quoted, you must use
- <code>quoteIdentifier()</code> as you form the string for the
- condition.
- </para>
- </note>
- <para>
- The second argument to the <code>where()</code> method is
- optional. It is a value to substitute into the expression.
- Zend_Db_Select quotes the value and substitutes it for a
- question-mark ("<code>?</code>") symbol in the expression.
- </para>
- <para>
- This method accepts only one parameter.
- If you have an expression into which you need to substitute
- multiple variables, you must format the string manually,
- interpolating variables and performing quoting yourself.
- </para>
- <example id="zend.db.select.building.where.example-param">
- <title>Example of a parameter in the where() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT product_id, product_name, price
- // FROM "products"
- // WHERE (price > 100.00)
- $minimumPrice = 100;
- $select = $db->select()
- ->from(
- 'products',
- array('product_id', 'product_name', 'price'))
- ->where('price > ?', $minimumPrice);]]></programlisting>
- </example>
- <para>
- You can invoke the <code>where()</code> method multiple times
- on the same Zend_Db_Select object. The resulting query combines
- the multiple terms together using <code>AND</code> between them.
- </para>
- <example id="zend.db.select.building.where.example-and">
- <title>Example of multiple where() methods</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT product_id, product_name, price
- // FROM "products"
- // WHERE (price > 100.00)
- // AND (price < 500.00)
- $minimumPrice = 100;
- $maximumPrice = 500;
- $select = $db->select()
- ->from('products',
- array('product_id', 'product_name', 'price'))
- ->where('price > ?', $minimumPrice)
- ->where('price < ?', $maximumPrice);]]></programlisting>
- </example>
- <para>
- If you need to combine terms together using <code>OR</code>,
- use the <code>orWhere()</code> method. This method is used
- in the same way as the <code>where()</code> method, except
- that the term specified is preceded by <code>OR</code>,
- instead of <code>AND</code>.
- </para>
- <example id="zend.db.select.building.where.example-or">
- <title>Example of the orWhere() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT product_id, product_name, price
- // FROM "products"
- // WHERE (price < 100.00)
- // OR (price > 500.00)
- $minimumPrice = 100;
- $maximumPrice = 500;
- $select = $db->select()
- ->from('products',
- array('product_id', 'product_name', 'price'))
- ->where('price < ?', $minimumPrice)
- ->orWhere('price > ?', $maximumPrice);]]></programlisting>
- </example>
- <para>
- Zend_Db_Select automatically puts parentheses around each
- expression you specify using the <code>where()</code> or
- <code>orWhere()</code> methods. This helps to ensure that
- Boolean operator precedence does not cause unexpected
- results.
- </para>
- <example id="zend.db.select.building.where.example-parens">
- <title>Example of parenthesizing Boolean expressions</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT product_id, product_name, price
- // FROM "products"
- // WHERE (price < 100.00 OR price > 500.00)
- // AND (product_name = 'Apple')
- $minimumPrice = 100;
- $maximumPrice = 500;
- $prod = 'Apple';
- $select = $db->select()
- ->from('products',
- array('product_id', 'product_name', 'price'))
- ->where("price < $minimumPrice OR price > $maximumPrice")
- ->where('product_name = ?', $prod);]]></programlisting>
- </example>
- <para>
- In the example above, the results would be quite different
- without the parentheses, because <code>AND</code> has higher
- precedence than <code>OR</code>. Zend_Db_Select applies the
- parentheses so the effect is that each expression in successive
- calls to the <code>where()</code> bind more tightly than the
- <code>AND</code> that combines the expressions.
- </para>
- </sect3>
- <sect3 id="zend.db.select.building.group">
- <title>Adding a GROUP BY Clause</title>
- <para>
- In SQL, the <code>GROUP BY</code> clause allows you
- to reduce the rows of a query result set to one row per
- unique value found in the column(s) named in the
- <code>GROUP BY</code> clause.
- </para>
- <para>
- In Zend_Db_Select, you can specify the column(s) to use
- for calculating the groups of rows using the
- <code>group()</code> method. The argument to this
- method is a column or an array of columns to use in
- the <code>GROUP BY</code> clause.
- </para>
- <example id="zend.db.select.building.group.example">
- <title>Example of the group() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", COUNT(*) AS line_items_per_product
- // FROM "products" AS p JOIN "line_items" AS l
- // ON p.product_id = l.product_id
- // GROUP BY p.product_id
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id'))
- ->join(array('l' => 'line_items'),
- 'p.product_id = l.product_id',
- array('line_items_per_product' => 'COUNT(*)'))
- ->group('p.product_id');]]></programlisting>
- </example>
- <para>
- Like the columns array in the <code>from()</code> method, you
- can use correlation names in the column name strings, and the
- column is quoted as an identifier unless the string contains
- parentheses or is an object of type Zend_Db_Expr.
- </para>
- </sect3>
- <sect3 id="zend.db.select.building.having">
- <title>Adding a HAVING Clause</title>
- <para>
- In SQL, the <code>HAVING</code> clause applies a restriction
- condition on groups of rows. This is similar to how a
- <code>WHERE</code> clause applies a restriction condition on rows.
- But the two clauses are different because <code>WHERE</code>
- conditions are applied before groups are defined, whereas
- <code>HAVING</code> conditions are applied after groups are
- defined.
- </para>
- <para>
- In Zend_Db_Select, you can specify conditions for restricting
- groups using the <code>having()</code> method. Its usage is
- similar to that of the <code>where()</code> method.
- The first argument is a string containing a SQL expression.
- The optional second argument is a value that is used to replace
- a positional parameter placeholder in the SQL expression.
- Expressions given in multiple invocations of the
- <code>having()</code> method are combined using the Boolean
- <code>AND</code> operator, or the <code>OR</code> operator if
- you use the <code>orHaving()</code> method.
- </para>
- <example id="zend.db.select.building.having.example">
- <title>Example of the having() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", COUNT(*) AS line_items_per_product
- // FROM "products" AS p JOIN "line_items" AS l
- // ON p.product_id = l.product_id
- // GROUP BY p.product_id
- // HAVING line_items_per_product > 10
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id'))
- ->join(array('l' => 'line_items'),
- 'p.product_id = l.product_id',
- array('line_items_per_product' => 'COUNT(*)'))
- ->group('p.product_id')
- ->having('line_items_per_product > 10');]]></programlisting>
- </example>
- <note>
- <para>
- No quoting is applied to expressions given to the
- <code>having()</code> or <code>orHaving()</code> methods.
- If you have column names that need to be quoted, you must use
- <code>quoteIdentifier()</code> as you form the string for the
- condition.
- </para>
- </note>
- </sect3>
- <sect3 id="zend.db.select.building.order">
- <title>Adding an ORDER BY Clause</title>
- <para>
- In SQL, the <code>ORDER BY</code> clause specifies one or more
- columns or expressions by which the result set of a query is
- sorted. If multiple columns are listed, the secondary columns
- are used to resolve ties; the sort order is determined by the
- secondary columns if the preceding columns contain identical
- values. The default sorting is from least value to greatest
- value. You can also sort by greatest value to least value for
- a given column in the list by specifying the keyword
- <code>DESC</code> after that column.
- </para>
- <para>
- In Zend_Db_Select, you can use the <code>order()</code> method
- to specify a column or an array of columns by which to sort.
- Each element of the array is a string naming a column.
- optionally with the <code>ASC</code> <code>DESC</code> keyword
- following it, separated by a space.
- </para>
- <para>
- Like in the <code>from()</code> and <code>group()</code>
- methods, column names are quoted as identifiers, unless they
- contain contain parentheses or are an object of type
- Zend_Db_Expr.
- </para>
- <example id="zend.db.select.building.order.example">
- <title>Example of the order() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", COUNT(*) AS line_items_per_product
- // FROM "products" AS p JOIN "line_items" AS l
- // ON p.product_id = l.product_id
- // GROUP BY p.product_id
- // ORDER BY "line_items_per_product" DESC, "product_id"
- $select = $db->select()
- ->from(array('p' => 'products'),
- array('product_id'))
- ->join(array('l' => 'line_items'),
- 'p.product_id = l.product_id',
- array('line_items_per_product' => 'COUNT(*)'))
- ->group('p.product_id')
- ->order(array('line_items_per_product DESC', 'product_id'));]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.limit">
- <title>Adding a LIMIT Clause</title>
- <para>
- Some RDBMS brands extend SQL with a query clause known as the
- <code>LIMIT</code> clause. This clause reduces the number of
- rows in the result set to at most a number you specify.
- You can also specify to skip a number of rows before starting
- to output.
- This feature makes it easy to take a subset of a result set,
- for example when displaying query results on progressive pages
- of output.
- </para>
- <para>
- In Zend_Db_Select, you can use the <code>limit()</code> method
- to specify the count of rows and the number of rows to skip.
- The first argument to this method is the desired count of rows.
- The second argument is the number of rows to skip.
- </para>
- <example id="zend.db.select.building.limit.example">
- <title>Example of the limit() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p
- // LIMIT 10, 20
- $select = $db->select()
- ->from(array('p' => 'products'), array('product_id', 'product_name'))
- ->limit(10, 20);]]></programlisting>
- </example>
- <note>
- <para>
- The <code>LIMIT</code> syntax is not supported by all RDBMS
- brands. Some RDBMS require different syntax to support
- similar functionality. Each Zend_Db_Adapter_Abstract class
- includes a method to produce SQL appropriate for that RDBMS.
- </para>
- </note>
- <para>
- Use the <code>limitPage()</code> method for an alternative way
- to specify row count and offset. This method allows you to
- limit the result set to one of a series of fixed-length subsets
- of rows from the query's total result set. In other words, you
- specify the length of a "page" of results, and the ordinal
- number of the single page of results you want the query to return.
- The page number is the first argument of the
- <code>limitPage()</code> method, and the page length is the
- second argument. Both arguments are required; they have no
- default values.
- </para>
- <example id="zend.db.select.building.limit.example2">
- <title>Example of the limitPage() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p
- // LIMIT 10, 20
- $select = $db->select()
- ->from(array('p' => 'products'), array('product_id', 'product_name'))
- ->limitPage(2, 10);]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.distinct">
- <title>Adding the DISTINCT Query Modifier</title>
- <para>
- The <code>distinct()</code> method enables you to add the
- <code>DISTINCT</code> keyword to your SQL query.
- </para>
- <example id="zend.db.select.building.distinct.example">
- <title>Example of the distinct() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT DISTINCT p."product_name"
- // FROM "products" AS p
- $select = $db->select()
- ->distinct()
- ->from(array('p' => 'products'), 'product_name');]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.building.for-update">
- <title>Adding the FOR UPDATE Query Modifier</title>
- <para>
- The <code>forUpdate()</code> method enables you to add the
- <code>FOR UPDATE</code> modifier to your SQL query.
- </para>
- <example id="zend.db.select.building.for-update.example">
- <title>Example of forUpdate() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT FOR UPDATE p.*
- // FROM "products" AS p
- $select = $db->select()
- ->forUpdate()
- ->from(array('p' => 'products'));]]></programlisting>
- </example>
- </sect3>
- </sect2>
- <sect2 id="zend.db.select.execute">
- <title>Executing Select Queries</title>
- <para>
- This section describes how to execute the query represented by a
- Zend_Db_Select object.
- </para>
- <sect3 id="zend.db.select.execute.query-adapter">
- <title>Executing Select Queries from the Db Adapter</title>
- <para>
- You can execute the query represented by the Zend_Db_Select
- object by passing it as the first argument to the
- <code>query()</code> method of a Zend_Db_Adapter_Abstract
- object. Use the Zend_Db_Select objects instead of a string
- query.
- </para>
- <para>
- The <code>query()</code> method returns an object of type
- Zend_Db_Statement or PDOStatement, depending on the adapter type.
- </para>
- <example id="zend.db.select.execute.query-adapter.example">
- <title>Example using the Db adapter's query() method</title>
- <programlisting role="php"><![CDATA[<?php
- $select = $db->select()
- ->from('products');
- $stmt = $db->query($select);
- $result = $stmt->fetchAll();]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.execute.query-select">
- <title>Executing Select Queries from the Object</title>
- <para>
- As an alternative to using the <code>query()</code> method
- of the adapter object, you can use the <code>query()</code>
- method of the Zend_Db_Select object.
- Both methods return an object of type Zend_Db_Statement or
- PDOStatement, depending on the adapter type.
- </para>
- <example id="zend.db.select.execute.query-select.example">
- <title>Example using the Select object's query method</title>
- <programlisting role="php"><![CDATA[<?php
- $select = $db->select()
- ->from('products');
- $stmt = $select->query();
- $result = $stmt->fetchAll();]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.execute.tostring">
- <title>Converting a Select Object to a SQL String</title>
- <para>
- If you need access to a string representation of the SQL
- query corresponding to the Zend_Db_Select object, use
- the <code>__toString()</code> method.
- </para>
- <example id="zend.db.select.execute.tostring.example">
- <title>Example of the __toString() method</title>
- <programlisting role="php"><![CDATA[<?php
- $select = $db->select()
- ->from('products');
- $sql = $select->__toString();
- echo "$sql\n";
- // The output is the string:
- // SELECT * FROM "products"]]></programlisting>
- </example>
- </sect3>
- </sect2>
- <sect2 id="zend.db.select.other">
- <title>Other methods</title>
- <para>
- This section describes other methods of the Zend_Db_Select class
- that are not covered above: <code>getPart()</code> and
- <code>reset()</code>.
- </para>
- <sect3 id="zend.db.select.other.get-part">
- <title>Retrieving Parts of the Select Object</title>
- <para>
- The <code>getPart()</code> method returns a representation
- of one part of your SQL query. For example, you can use this
- method to return the array of expressions for the
- <code>WHERE</code> clause, or the array of columns
- (or column expressions) that are in the <code>SELECT</code>
- list, or the values of the count and offset for the
- <code>LIMIT</code> clause.
- </para>
- <para>
- The return value is not a string containing a fragment of SQL
- syntax. The return value is an internal representation, which
- is typically an array structure containing values and
- expressions. Each part of the query has a different structure.
- </para>
- <para>
- The single argument to the <code>getPart()</code> method is
- a string that identifies which part of the Select query to
- return. For example, the string <code>'from'</code>
- identifies the part of the Select object that stores
- information about the tables in the <code>FROM</code> clause,
- including joined tables.
- </para>
- <para>
- The Zend_Db_Select class defines constants you can use for
- parts of the SQL query. You can use these constant definitions,
- or you can the literal strings.
- </para>
- <table id="zend.db.select.other.get-part.table">
- <title>Constants used by getPart() and reset()</title>
- <tgroup cols="2">
- <thead>
- <row>
- <entry>Constant</entry>
- <entry>String value</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry><code>Zend_Db_Select::DISTINCT</code></entry>
- <entry><code>'distinct'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::FOR_UPDATE</code></entry>
- <entry><code>'forupdate'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::COLUMNS</code></entry>
- <entry><code>'columns'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::FROM</code></entry>
- <entry><code>'from'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::WHERE</code></entry>
- <entry><code>'where'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::GROUP</code></entry>
- <entry><code>'group'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::HAVING</code></entry>
- <entry><code>'having'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::ORDER</code></entry>
- <entry><code>'order'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::LIMIT_COUNT</code></entry>
- <entry><code>'limitcount'</code></entry>
- </row>
- <row>
- <entry><code>Zend_Db_Select::LIMIT_OFFSET</code></entry>
- <entry><code>'limitoffset'</code></entry>
- </row>
- </tbody>
- </tgroup>
- </table>
- <example id="zend.db.select.other.get-part.example">
- <title>Example of the getPart() method</title>
- <programlisting role="php"><![CDATA[<?php
- $select = $db->select()
- ->from('products')
- ->order('product_id');
- // You can use a string literal to specify the part
- $orderData = $select->getPart( 'order' );
- // You can use a constant to specify the same part
- $orderData = $select->getPart( Zend_Db_Select::ORDER );
- // The return value may be an array structure, not a string.
- // Each part has a different structure.
- print_r( $orderData );]]></programlisting>
- </example>
- </sect3>
- <sect3 id="zend.db.select.other.reset">
- <title>Resetting Parts of the Select Object</title>
- <para>
- The <code>reset()</code> method enables you to clear one
- specified part of the SQL query, or else clear all parts of
- the SQL query if you omit the argument.
- </para>
- <para>
- The single argument is optional. You can specify the part
- of the query to clear, using the same strings you used in
- the argument to the <code>getPart()</code> method.
- The part of the query you specify is reset to a default state.
- </para>
- <para>
- If you omit the parameter, <code>reset()</code> changes all
- parts of the query to their default state. This makes the
- Zend_Db_Select object equivalent to a new object, as though you
- had just instantiated it.
- </para>
- <example id="zend.db.select.other.reset.example">
- <title>Example of the reset() method</title>
- <programlisting role="php"><![CDATA[<?php
- // Build this query:
- // SELECT p.*
- // FROM "products" AS p
- // ORDER BY "product_name"
- $select = $db->select()
- ->from(array('p' => 'products')
- ->order('product_name');
- // Changed requirement, instead order by a different columns:
- // SELECT p.*
- // FROM "products" AS p
- // ORDER BY "product_id"
- // Clear one part so we can redefine it
- $select->reset( Zend_Db_Select::ORDER );
- // And specify a different column
- $select->order('product_id');
- // Clear all parts of the query
- $select->reset();]]></programlisting>
- </example>
- </sect3>
- </sect2>
- </sect1>
- <!--
- vim:se ts=4 sw=4 et:
- -->
|