Zend_Db_Select.xml 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. <sect1 id="zend.db.select">
  2. <title>Zend_Db_Select</title>
  3. <sect2 id="zend.db.select.introduction">
  4. <title>Visão Geral do Objeto Select</title>
  5. <para>
  6. O objeto Zend_Db_Select representa um comando de consulta SQL <code>SELECT</code>.
  7. A classe possui métodos para a adição de partes individuais em uma query. Você
  8. pode especificar algumas partes da consulta usando métodos PHP e estruturas de
  9. dados, e a classe se encarrega de formar a sintaxe SQL correta para você. Depois
  10. da construção de uma consulta, você pode executá-la como se você houvesse a escrito
  11. em uma string.
  12. </para>
  13. <para>
  14. As vantagens oferecidas pelo Zend_Db_Select incluem:
  15. </para>
  16. <itemizedlist>
  17. <listitem>
  18. <para>
  19. Métodos orientados a objetos para especificação de consultas SQL
  20. de maneira "piece-by-piece" (aos pedaços ou em partes);
  21. </para>
  22. </listitem>
  23. <listitem>
  24. <para>
  25. Abstração de independência de base de dados de algumas partes
  26. da consulta SQL;
  27. </para>
  28. </listitem>
  29. <listitem>
  30. <para>
  31. Colocação automática de aspas nos identificadores de metadados na maioria
  32. dos casos, para dar suporte aos identificadores que contém palavras SQL reservadas
  33. e caracteres especiais;
  34. </para>
  35. </listitem>
  36. <listitem>
  37. <para>
  38. Colocação automática de aspas nos identificadores e valores, para ajudar
  39. na redução de ataques por "SQL injection".
  40. </para>
  41. </listitem>
  42. </itemizedlist>
  43. <para>
  44. A utilização de Zend_Db_Select não é obrigatória. Para consultas SELECT
  45. muito simples, normalmente é mais fácil escrever toda a consulta SQL
  46. em uma string e executá-la usando métodos da classe Adapter, como o
  47. <code>query()</code> ou <code>fetchAll()</code>. O uso de Zend_Db_Select
  48. é muito útil quando você precisa montar uma consulta SELECT usando "procedures"
  49. (através de procedimentos), ou quando você precisa montar a consulta baseando-se
  50. na lógica condicional da sua aplicação.
  51. </para>
  52. </sect2>
  53. <sect2 id="zend.db.select.creating">
  54. <title>Criando um Objeto Select</title>
  55. <para>
  56. Você pode criar uma instância de um objeto Zend_Db_Select
  57. usando o método <code>select()</code> de um objeto Zend_Db_Adapter_Abstract.
  58. </para>
  59. <example id="zend.db.select.creating.example-db">
  60. <title>Exemplo do método select() do adaptador para bases de dados</title>
  61. <programlisting role="php"><![CDATA[<?php
  62. $db = Zend_Db::factory( ...options... );
  63. $select = $db->select();]]></programlisting>
  64. </example>
  65. <para>
  66. Outra forma de criar um objeto Zend_Db_Select é com o
  67. construtor dele, especificando o adaptador como parâmetro.
  68. </para>
  69. <example id="zend.db.select.creating.example-new">
  70. <title>Examplo da criação de um novo objeto Select</title>
  71. <programlisting role="php"><![CDATA[<?php
  72. $db = Zend_Db::factory( ...options... );
  73. $select = new Zend_Db_Select($db);]]></programlisting>
  74. </example>
  75. </sect2>
  76. <sect2 id="zend.db.select.building">
  77. <title>Construindo Consultas Select</title>
  78. <para>
  79. Ao contruir um consulta, você pode adicionar cláusulas uma por uma.
  80. Existe um método diferente para cada cláusula no objeto.
  81. </para>
  82. <example id="zend.db.select.building.example">
  83. <title>Exemplo do uso de métodos para adicionar cláusulas</title>
  84. <programlisting role="php"><![CDATA[<?php
  85. // Create the Zend_Db_Select object
  86. $select = $db->select();
  87. // Add a FROM clause
  88. $select->from( ...specify table and columns... )
  89. // Add a WHERE clause
  90. $select->where( ...specify search criteria... )
  91. // Add an ORDER BY clause
  92. $select->order( ...specify sorting criteria... );]]></programlisting>
  93. </example>
  94. <para>
  95. Você também pode usar a maior parte dos métodos do objeto Zend_Db_Select
  96. com uma interface "fluent" conveniente. Uma interface "fluent" significa que cada
  97. método retorna uma referência para o objeto no qual foi chamado, então você pode
  98. imediatamente chamar outro método.
  99. </para>
  100. <example id="zend.db.select.building.example-fluent">
  101. <title>Examplo de uso da interface "fluent"</title>
  102. <programlisting role="php"><![CDATA[<?php
  103. $select = $db->select()
  104. ->from( ...specify table and columns... )
  105. ->where( ...specify search criteria... )
  106. ->order( ...specify sorting criteria... );]]></programlisting>
  107. </example>
  108. <para>
  109. Os exemplos nesta seção mostram o uso da interface "fluent",
  110. mas você pode usar a interface "non-fluent" em todos os casos.
  111. É freqüentemente necessário usar a interface "non-fluent" quando, por exemplo,
  112. sua aplicação precisa executar alguma lógica antes de adicionar uma cláusula
  113. a uma consulta.
  114. </para>
  115. <sect3 id="zend.db.select.building.from">
  116. <title>Adicionando uma cláusula FROM</title>
  117. <para>
  118. Especifique a tabela para esta consulta usando o método <code>from()</code>.
  119. Você pode especificar o nome da tabela como uma simples string.
  120. Zend_Db_Select coloca o entre aspas o nome da tabela, então, você pode
  121. usar caracteres especiais.
  122. </para>
  123. <example id="zend.db.select.building.from.example">
  124. <title>Example of the from() method</title>
  125. <programlisting role="php"><![CDATA[<?php
  126. // Build this query:
  127. // SELECT *
  128. // FROM "products"
  129. $select = $db->select()
  130. ->from( 'products' );]]></programlisting>
  131. </example>
  132. <para>
  133. You can also specify the correlation name (sometimes called the
  134. "table alias") for a table. Instead of a simple string, use an
  135. associative array mapping the correlation name to the table
  136. name. In other clauses of the SQL query, use this correlation
  137. name. If your query joins more than one table, Zend_Db_Select
  138. generates unique correlation names based on the table names,
  139. for any tables for which you don't specify the correlation name.
  140. </para>
  141. <example id="zend.db.select.building.from.example-cname">
  142. <title>Example of specifying a table correlation name</title>
  143. <programlisting role="php"><![CDATA[<?php
  144. // Build this query:
  145. // SELECT p.*
  146. // FROM "products" AS p
  147. $select = $db->select()
  148. ->from( array('p' => 'products') );]]></programlisting>
  149. </example>
  150. <para>
  151. Algumas marcas de RDBMS dão suporte a um especificador de schema
  152. para uma tabela. Você pode especificar o nome a tabela como
  153. "<code>schemaName.tableName</code>", onde Zend_Db_Select coloca entre aspas
  154. cada uma das partes individualmente, ou então você deve especificar o nome
  155. do schema separadamente. Um nome de schema especificado no nome da tabela
  156. precede um schema fornecido separadamente se eventualmente ambos forem
  157. informados.
  158. </para>
  159. <example id="zend.db.select.building.from.example-schema">
  160. <title>Exemplo de especificação de nome de schema</title>
  161. <programlisting role="php"><![CDATA[<?php
  162. // Build this query:
  163. // SELECT *
  164. // FROM "myschema"."products"
  165. $select = $db->select()
  166. ->from( 'myschema.products' );
  167. // or
  168. $select = $db->select()
  169. ->from('products', '*', 'myschema');]]></programlisting>
  170. </example>
  171. </sect3>
  172. <sect3 id="zend.db.select.building.columns">
  173. <title>Adicionando Colunas</title>
  174. <para>
  175. No segundo argumento do método <code>from()</code> ,
  176. você pode especificaras colunas a serem selecionadas da
  177. respectiva tabela. Se você não especificar nenhuma coluna,
  178. o valor padrão é "<code>*</code>", o caracter curinga para "todas as colunas".
  179. </para>
  180. <para>
  181. Você pode listar as colunas em um simples array de strings, ou como
  182. um mapeamento associativo do alias da coluna para nome da coluna.
  183. Se você só tiver uma coluna para consultar, e não precisar indicar um
  184. alias, você pode listá-la em uma string simples ao invés de um array.
  185. </para>
  186. <para>
  187. Se você passar um array vazio como o argumento de colunas, nenhuma
  188. coluna da respectiva tabela será incluída no result set.
  189. 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>.
  190. </para>
  191. <para>
  192. Você pode especificar o nome da coluna como
  193. "<code>correlationName.columnName</code>".
  194. Zend_Db_Select os coloca entre aspas individualmente.
  195. Caso você não especifique o nome da correlação para uma coluna,
  196. é usado o nome da correlação da tabela indicada no método<code>from()</code>.
  197. </para>
  198. <example id="zend.db.select.building.columns.example">
  199. <title>Examples of specifying columns</title>
  200. <programlisting role="php"><![CDATA[<?php
  201. // Build this query:
  202. // SELECT p."product_id", p."product_name"
  203. // FROM "products" AS p
  204. $select = $db->select()
  205. ->from(array('p' => 'products'),
  206. array('product_id', 'product_name'));
  207. // Build the same query, specifying correlation names:
  208. // SELECT p."product_id", p."product_name"
  209. // FROM "products" AS p
  210. $select = $db->select()
  211. ->from(array('p' => 'products'),
  212. array('p.product_id', 'p.product_name'));
  213. // Build this query with an alias for one column:
  214. // SELECT p."product_id" AS prodno, p."product_name"
  215. // FROM "products" AS p
  216. $select = $db->select()
  217. ->from(array('p' => 'products'),
  218. array('prodno' => 'product_id', 'product_name'));]]></programlisting>
  219. </example>
  220. </sect3>
  221. <sect3 id="zend.db.select.building.columns-expr">
  222. <title>Adicionando Colunas de Expressões</title>
  223. <para>
  224. Algumas vezes as colunas de uma consulta SQL são expressões, e não
  225. simplesmente o nome de uma couna da tabela. Expressões não devem usar
  226. nomes de correlação ou aspas. Se a string da coluna possuir parênteses,
  227. Zend_Db_Select a reconhecerá como uma expressão.
  228. </para>
  229. <para>
  230. Você também pode criar um objeto do tipo Zend_Db_Expr explicitamente,
  231. para prevenir que uma string seja tratada como um nome de coluna.
  232. Zend_Db_Expr é uma classe diminuta que contém uma única string.
  233. Zend_Db_Select reconhece obtejos do tipo Zend_Db_Expr e os converte
  234. novamente para strings, mas não efetua qualquer alteração como a
  235. colocação de aspas ou nomes de correlação.
  236. </para>
  237. <note>
  238. <para>
  239. O uso de Zend_Db_Expr para nomes de colunas não é necessário se as
  240. expressões contiverem parênteses; Zend_Db_Select reconhece os parênteses
  241. e trata a string como uma expresão, ignorando a colocação de aspas e de
  242. nomes de correlação.
  243. </para>
  244. </note>
  245. <example id="zend.db.select.building.columns-expr.example">
  246. <title>Exemplos de especificação de colunas contendo expressões</title>
  247. <programlisting role="php"><![CDATA[<?php
  248. // Build this query:
  249. // SELECT p."product_id", LOWER(product_name)
  250. // FROM "products" AS p
  251. // An expression with parentheses implicitly becomes
  252. // a Zend_Db_Expr.
  253. $select = $db->select()
  254. ->from(array('p' => 'products'),
  255. array('product_id', 'LOWER(product_name)'));
  256. // Build this query:
  257. // SELECT p."product_id", (p.cost * 1.08) AS cost_plus_tax
  258. // FROM "products" AS p
  259. $select = $db->select()
  260. ->from(array('p' => 'products'),
  261. array('product_id', 'cost_plus_tax' => '(p.cost * 1.08)'));
  262. // Build this query using Zend_Db_Expr explicitly:
  263. // SELECT p."product_id", p.cost * 1.08 AS cost_plus_tax
  264. // FROM "products" AS p
  265. $select = $db->select()
  266. ->from(array('p' => 'products'),
  267. array('product_id', 'cost_plus_tax' => new Zend_Db_Expr('p.cost * 1.08')));]]></programlisting>
  268. </example>
  269. <para>
  270. Nos casos acima, Zend_Db_Select não altera a string
  271. para colocar os nomes de correlação ou aspas. Se as
  272. mudanças forem necessárias para evitar alguma ambiguidade,
  273. você deve fazê-las manualmente na string.
  274. </para>
  275. <para>
  276. Se os nomes das colunas são palavras-chave SQL ou possuem
  277. caracteres especiais, você deve usar o método <code>quoteIdentifier()</code>
  278. da classe Adapter, e interpolar o resultado na string. O método
  279. <code>quoteIdentifier()</code> usa aspas no SQL para delimitar o identificador,
  280. o que deixa claro que ele é um identificador de uma tabela ou coluna e não
  281. parte da síntaxe SQL.
  282. </para>
  283. <para>
  284. Seu código fica mais independente de base de dados se você
  285. usar o método <code>quoteIdentifier()</code> ao invés de digitar
  286. as aspas nas strings porque algumas marcas de SGBD Relacionais usam
  287. símbolos fora do padrão para referenciar identificadores.
  288. O método <code>quoteIdentifier()</code> é projetado para usar
  289. os símbolos de referência apropriados de acordo com o tipo de adaptador.
  290. O método <code>quoteIdentifier()</code> também ignora qualquer
  291. caracter de referência que aparecer no nome de um identificador.
  292. </para>
  293. <example id="zend.db.select.building.columns-quoteid.example">
  294. <title>Examples of quoting columns in an expression</title>
  295. <programlisting role="php"><![CDATA[<?php
  296. // Build this query, quoting a special column name "from" in the expression:
  297. // SELECT p."from" + 10 AS origin
  298. // FROM "products" AS p
  299. $select = $db->select()
  300. ->from(array('p' => 'products'),
  301. array('origin' => '(p.' . $db->quoteIdentifier('from') . ' + 10)'));]]></programlisting>
  302. </example>
  303. </sect3>
  304. <sect3 id="zend.db.select.building.join">
  305. <title>Adding Another Table to the Query with JOIN</title>
  306. <para>
  307. Many useful queries involve using a <code>JOIN</code>
  308. to combine rows from multiple tables. You can add
  309. tables to a Zend_Db_Select query using the
  310. <code>join()</code> method. Using this method is
  311. similar to the <code>from()</code> method, except
  312. you can also specify a join condition in most cases.
  313. </para>
  314. <example id="zend.db.select.building.join.example">
  315. <title>Example of the join() method</title>
  316. <programlisting role="php"><![CDATA[<?php
  317. // Build this query:
  318. // SELECT p."product_id", p."product_name", l.*
  319. // FROM "products" AS p JOIN "line_items" AS l
  320. // ON p.product_id = l.product_id
  321. $select = $db->select()
  322. ->from(array('p' => 'products'),
  323. array('product_id', 'product_name'))
  324. ->join(array('l' => 'line_items'),
  325. 'p.product_id = l.product_id');]]></programlisting>
  326. </example>
  327. <para>
  328. The second argument to <code>join()</code> is a string
  329. that is the join condition. This is an expression that
  330. declares the criteria by which rows in one table match
  331. rows in the the other table. You can use correlation
  332. names in this expression.
  333. </para>
  334. <note>
  335. <para>
  336. No quoting is applied to the expression you specify
  337. for the join condition; if you have column names that need
  338. to be quoted, you must use <code>quoteIdentifier()</code>
  339. as you form the string for the join condition.
  340. </para>
  341. </note>
  342. <para>
  343. The third argument to <code>join()</code> is an array
  344. of column names, like that used in the <code>from()</code>
  345. method. It defaults to "<code>*</code>", supports correlation
  346. names, expressions, and Zend_Db_Expr in the same way as the
  347. array of column names in the <code>from()</code> method.
  348. </para>
  349. <para>
  350. To select no columns from a table, use an empty array for
  351. the list of columns. This usage works in the
  352. <code>from()</code> method too, but typically you want
  353. some columns from the primary table in your queries,
  354. whereas you might want no columns from a joined table.
  355. </para>
  356. <example id="zend.db.select.building.join.example-no-columns">
  357. <title>Example of specifying no columns</title>
  358. <programlisting role="php"><![CDATA[<?php
  359. // Build this query:
  360. // SELECT p."product_id", p."product_name"
  361. // FROM "products" AS p JOIN "line_items" AS l
  362. // ON p.product_id = l.product_id
  363. $select = $db->select()
  364. ->from(array('p' => 'products'),
  365. array('product_id', 'product_name'))
  366. ->join(array('l' => 'line_items'),
  367. 'p.product_id = l.product_id',
  368. array() ); // empty list of columns]]></programlisting>
  369. <para>
  370. Note the empty <code>array()</code> in the above example
  371. in place of a list of columns from the joined table.
  372. </para>
  373. </example>
  374. <para>
  375. SQL has several types of joins.
  376. See the list below for the methods to support
  377. different join types in Zend_Db_Select.
  378. </para>
  379. <itemizedlist>
  380. <listitem>
  381. <para>
  382. <command>INNER JOIN</command> with the
  383. <code>join(table, join, [columns])</code>
  384. or <code>joinInner(table, join, [columns])</code> methods.
  385. </para>
  386. <para>
  387. This may be the most common type of join. Rows from
  388. each table are compared using the join condition you
  389. specify. The result set includes only the rows that
  390. satisfy the join condition. The result set can be
  391. empty if no rows satisfy this condition.
  392. </para>
  393. <para>
  394. All RDBMS brands support this join type.
  395. </para>
  396. </listitem>
  397. <listitem>
  398. <para>
  399. <command>LEFT JOIN</command> with the
  400. <code>joinLeft(table, condition, [columns])</code> method.
  401. </para>
  402. <para>
  403. All rows from the left operand table are included,
  404. matching rows from the right operand table included,
  405. and the columns from the right operand table are filled
  406. with NULLs if no row exists matching the left table.
  407. </para>
  408. <para>
  409. All RDBMS brands support this join type.
  410. </para>
  411. </listitem>
  412. <listitem>
  413. <para>
  414. <command>RIGHT JOIN</command> with the
  415. <code>joinRight(table, condition, [columns])</code> method.
  416. </para>
  417. <para>
  418. Right outer join is the complement of left outer join.
  419. All rows from the right operand table are included,
  420. matching rows from the left operand table included,
  421. and the columns from the left operand table are filled
  422. with NULLs if no row exists matching the right table.
  423. </para>
  424. <para>
  425. Some RDBMS brands don't support this join type, but
  426. in general any right join can be represented as a left
  427. join by reversing the order of the tables.
  428. </para>
  429. </listitem>
  430. <listitem>
  431. <para>
  432. <command>FULL JOIN</command> with the
  433. <code>joinFull(table, condition, [columns])</code> method.
  434. </para>
  435. <para>
  436. A full outer join is like combining a left outer join
  437. and a right outer join. All rows from both tables are
  438. included, paired with each other on the same row of the
  439. result set if they satisfy the join condition, and
  440. otherwise paired with NULLs in place of columns from the
  441. other table.
  442. </para>
  443. <para>
  444. Some RDBMS brands don't support this join type.
  445. </para>
  446. </listitem>
  447. <listitem>
  448. <para>
  449. <command>CROSS JOIN</command> with the
  450. <code>joinCross(table, [columns])</code> method.
  451. </para>
  452. <para>
  453. A cross join is a Cartesian product.
  454. Every row in the first table is matched to every
  455. row in the second table. Therefore the number of
  456. rows in the result set is equal to the product of
  457. the number of rows in each table. You can filter
  458. the result set using conditions in a WHERE clause;
  459. in this way a cross join is similar to the old SQL-89
  460. join syntax.
  461. </para>
  462. <para>
  463. The <code>joinCross()</code> method has no parameter
  464. to specify the join condition.
  465. Some RDBMS brands don't support this join type.
  466. </para>
  467. </listitem>
  468. <listitem>
  469. <para>
  470. <command>NATURAL JOIN</command> with the
  471. <code>joinNatural(table, [columns])</code> method.
  472. </para>
  473. <para>
  474. A natural join compares any column(s) that appear with
  475. the same name in both tables. The comparison is
  476. equality of all the column(s); comparing the columns
  477. using inequality is not a natural join.
  478. Only natural inner joins are supported by this API,
  479. even though SQL permits natural outer joins as well.
  480. </para>
  481. <para>
  482. The <code>joinNatural()</code> method has no parameter
  483. to specify the join condition.
  484. </para>
  485. </listitem>
  486. </itemizedlist>
  487. </sect3>
  488. <sect3 id="zend.db.select.building.where">
  489. <title>Adding a WHERE Clause</title>
  490. <para>
  491. You can specify criteria for restricting rows of the result set
  492. using the <code>where()</code> method. The first argument of
  493. this method is a SQL expression, and this expression is used
  494. in a SQL <code>WHERE</code> clause in the query.
  495. </para>
  496. <example id="zend.db.select.building.where.example">
  497. <title>Example of the where() method</title>
  498. <programlisting role="php"><![CDATA[<?php
  499. // Build this query:
  500. // SELECT product_id, product_name, price
  501. // FROM "products"
  502. // WHERE price > 100.00
  503. $select = $db->select()
  504. ->from(
  505. 'products',
  506. array('product_id', 'product_name', 'price'))
  507. ->where('price > 100.00');]]></programlisting>
  508. </example>
  509. <note>
  510. <para>
  511. No quoting is applied to expressions given to the
  512. <code>where()</code> or <code>orWhere()</code> methods.
  513. If you have column names that need to be quoted, you must use
  514. <code>quoteIdentifier()</code> as you form the string for the
  515. condition.
  516. </para>
  517. </note>
  518. <para>
  519. The second argument to the <code>where()</code> method is
  520. optional. It is a value to substitute into the expression.
  521. Zend_Db_Select quotes the value and substitutes it for a
  522. question-mark ("<code>?</code>") symbol in the expression.
  523. </para>
  524. <para>
  525. This method accepts only one parameter.
  526. If you have an expression into which you need to substitute
  527. multiple variables, you must format the string manually,
  528. interpolating variables and performing quoting yourself.
  529. </para>
  530. <example id="zend.db.select.building.where.example-param">
  531. <title>Example of a parameter in the where() method</title>
  532. <programlisting role="php"><![CDATA[<?php
  533. // Build this query:
  534. // SELECT product_id, product_name, price
  535. // FROM "products"
  536. // WHERE (price > 100.00)
  537. $minimumPrice = 100;
  538. $select = $db->select()
  539. ->from(
  540. 'products',
  541. array('product_id', 'product_name', 'price'))
  542. ->where('price > ?', $minimumPrice);]]></programlisting>
  543. </example>
  544. <para>
  545. You can invoke the <code>where()</code> method multiple times
  546. on the same Zend_Db_Select object. The resulting query combines
  547. the multiple terms together using <code>AND</code> between them.
  548. </para>
  549. <example id="zend.db.select.building.where.example-and">
  550. <title>Example of multiple where() methods</title>
  551. <programlisting role="php"><![CDATA[<?php
  552. // Build this query:
  553. // SELECT product_id, product_name, price
  554. // FROM "products"
  555. // WHERE (price > 100.00)
  556. // AND (price < 500.00)
  557. $minimumPrice = 100;
  558. $maximumPrice = 500;
  559. $select = $db->select()
  560. ->from('products',
  561. array('product_id', 'product_name', 'price'))
  562. ->where('price > ?', $minimumPrice)
  563. ->where('price < ?', $maximumPrice);]]></programlisting>
  564. </example>
  565. <para>
  566. If you need to combine terms together using <code>OR</code>,
  567. use the <code>orWhere()</code> method. This method is used
  568. in the same way as the <code>where()</code> method, except
  569. that the term specified is preceded by <code>OR</code>,
  570. instead of <code>AND</code>.
  571. </para>
  572. <example id="zend.db.select.building.where.example-or">
  573. <title>Example of the orWhere() method</title>
  574. <programlisting role="php"><![CDATA[<?php
  575. // Build this query:
  576. // SELECT product_id, product_name, price
  577. // FROM "products"
  578. // WHERE (price < 100.00)
  579. // OR (price > 500.00)
  580. $minimumPrice = 100;
  581. $maximumPrice = 500;
  582. $select = $db->select()
  583. ->from('products',
  584. array('product_id', 'product_name', 'price'))
  585. ->where('price < ?', $minimumPrice)
  586. ->orWhere('price > ?', $maximumPrice);]]></programlisting>
  587. </example>
  588. <para>
  589. Zend_Db_Select automatically puts parentheses around each
  590. expression you specify using the <code>where()</code> or
  591. <code>orWhere()</code> methods. This helps to ensure that
  592. Boolean operator precedence does not cause unexpected
  593. results.
  594. </para>
  595. <example id="zend.db.select.building.where.example-parens">
  596. <title>Example of parenthesizing Boolean expressions</title>
  597. <programlisting role="php"><![CDATA[<?php
  598. // Build this query:
  599. // SELECT product_id, product_name, price
  600. // FROM "products"
  601. // WHERE (price < 100.00 OR price > 500.00)
  602. // AND (product_name = 'Apple')
  603. $minimumPrice = 100;
  604. $maximumPrice = 500;
  605. $prod = 'Apple';
  606. $select = $db->select()
  607. ->from('products',
  608. array('product_id', 'product_name', 'price'))
  609. ->where("price < $minimumPrice OR price > $maximumPrice")
  610. ->where('product_name = ?', $prod);]]></programlisting>
  611. </example>
  612. <para>
  613. In the example above, the results would be quite different
  614. without the parentheses, because <code>AND</code> has higher
  615. precedence than <code>OR</code>. Zend_Db_Select applies the
  616. parentheses so the effect is that each expression in successive
  617. calls to the <code>where()</code> bind more tightly than the
  618. <code>AND</code> that combines the expressions.
  619. </para>
  620. </sect3>
  621. <sect3 id="zend.db.select.building.group">
  622. <title>Adding a GROUP BY Clause</title>
  623. <para>
  624. In SQL, the <code>GROUP BY</code> clause allows you
  625. to reduce the rows of a query result set to one row per
  626. unique value found in the column(s) named in the
  627. <code>GROUP BY</code> clause.
  628. </para>
  629. <para>
  630. In Zend_Db_Select, you can specify the column(s) to use
  631. for calculating the groups of rows using the
  632. <code>group()</code> method. The argument to this
  633. method is a column or an array of columns to use in
  634. the <code>GROUP BY</code> clause.
  635. </para>
  636. <example id="zend.db.select.building.group.example">
  637. <title>Example of the group() method</title>
  638. <programlisting role="php"><![CDATA[<?php
  639. // Build this query:
  640. // SELECT p."product_id", COUNT(*) AS line_items_per_product
  641. // FROM "products" AS p JOIN "line_items" AS l
  642. // ON p.product_id = l.product_id
  643. // GROUP BY p.product_id
  644. $select = $db->select()
  645. ->from(array('p' => 'products'),
  646. array('product_id'))
  647. ->join(array('l' => 'line_items'),
  648. 'p.product_id = l.product_id',
  649. array('line_items_per_product' => 'COUNT(*)'))
  650. ->group('p.product_id');]]></programlisting>
  651. </example>
  652. <para>
  653. Like the columns array in the <code>from()</code> method, you
  654. can use correlation names in the column name strings, and the
  655. column is quoted as an identifier unless the string contains
  656. parentheses or is an object of type Zend_Db_Expr.
  657. </para>
  658. </sect3>
  659. <sect3 id="zend.db.select.building.having">
  660. <title>Adding a HAVING Clause</title>
  661. <para>
  662. In SQL, the <code>HAVING</code> clause applies a restriction
  663. condition on groups of rows. This is similar to how a
  664. <code>WHERE</code> clause applies a restriction condition on rows.
  665. But the two clauses are different because <code>WHERE</code>
  666. conditions are applied before groups are defined, whereas
  667. <code>HAVING</code> conditions are applied after groups are
  668. defined.
  669. </para>
  670. <para>
  671. In Zend_Db_Select, you can specify conditions for restricting
  672. groups using the <code>having()</code> method. Its usage is
  673. similar to that of the <code>where()</code> method.
  674. The first argument is a string containing a SQL expression.
  675. The optional second argument is a value that is used to replace
  676. a positional parameter placeholder in the SQL expression.
  677. Expressions given in multiple invocations of the
  678. <code>having()</code> method are combined using the Boolean
  679. <code>AND</code> operator, or the <code>OR</code> operator if
  680. you use the <code>orHaving()</code> method.
  681. </para>
  682. <example id="zend.db.select.building.having.example">
  683. <title>Example of the having() method</title>
  684. <programlisting role="php"><![CDATA[<?php
  685. // Build this query:
  686. // SELECT p."product_id", COUNT(*) AS line_items_per_product
  687. // FROM "products" AS p JOIN "line_items" AS l
  688. // ON p.product_id = l.product_id
  689. // GROUP BY p.product_id
  690. // HAVING line_items_per_product > 10
  691. $select = $db->select()
  692. ->from(array('p' => 'products'),
  693. array('product_id'))
  694. ->join(array('l' => 'line_items'),
  695. 'p.product_id = l.product_id',
  696. array('line_items_per_product' => 'COUNT(*)'))
  697. ->group('p.product_id')
  698. ->having('line_items_per_product > 10');]]></programlisting>
  699. </example>
  700. <note>
  701. <para>
  702. No quoting is applied to expressions given to the
  703. <code>having()</code> or <code>orHaving()</code> methods.
  704. If you have column names that need to be quoted, you must use
  705. <code>quoteIdentifier()</code> as you form the string for the
  706. condition.
  707. </para>
  708. </note>
  709. </sect3>
  710. <sect3 id="zend.db.select.building.order">
  711. <title>Adding an ORDER BY Clause</title>
  712. <para>
  713. In SQL, the <code>ORDER BY</code> clause specifies one or more
  714. columns or expressions by which the result set of a query is
  715. sorted. If multiple columns are listed, the secondary columns
  716. are used to resolve ties; the sort order is determined by the
  717. secondary columns if the preceding columns contain identical
  718. values. The default sorting is from least value to greatest
  719. value. You can also sort by greatest value to least value for
  720. a given column in the list by specifying the keyword
  721. <code>DESC</code> after that column.
  722. </para>
  723. <para>
  724. In Zend_Db_Select, you can use the <code>order()</code> method
  725. to specify a column or an array of columns by which to sort.
  726. Each element of the array is a string naming a column.
  727. optionally with the <code>ASC</code> <code>DESC</code> keyword
  728. following it, separated by a space.
  729. </para>
  730. <para>
  731. Like in the <code>from()</code> and <code>group()</code>
  732. methods, column names are quoted as identifiers, unless they
  733. contain contain parentheses or are an object of type
  734. Zend_Db_Expr.
  735. </para>
  736. <example id="zend.db.select.building.order.example">
  737. <title>Example of the order() method</title>
  738. <programlisting role="php"><![CDATA[<?php
  739. // Build this query:
  740. // SELECT p."product_id", COUNT(*) AS line_items_per_product
  741. // FROM "products" AS p JOIN "line_items" AS l
  742. // ON p.product_id = l.product_id
  743. // GROUP BY p.product_id
  744. // ORDER BY "line_items_per_product" DESC, "product_id"
  745. $select = $db->select()
  746. ->from(array('p' => 'products'),
  747. array('product_id'))
  748. ->join(array('l' => 'line_items'),
  749. 'p.product_id = l.product_id',
  750. array('line_items_per_product' => 'COUNT(*)'))
  751. ->group('p.product_id')
  752. ->order(array('line_items_per_product DESC', 'product_id'));]]></programlisting>
  753. </example>
  754. </sect3>
  755. <sect3 id="zend.db.select.building.limit">
  756. <title>Adding a LIMIT Clause</title>
  757. <para>
  758. Some RDBMS brands extend SQL with a query clause known as the
  759. <code>LIMIT</code> clause. This clause reduces the number of
  760. rows in the result set to at most a number you specify.
  761. You can also specify to skip a number of rows before starting
  762. to output.
  763. This feature makes it easy to take a subset of a result set,
  764. for example when displaying query results on progressive pages
  765. of output.
  766. </para>
  767. <para>
  768. In Zend_Db_Select, you can use the <code>limit()</code> method
  769. to specify the count of rows and the number of rows to skip.
  770. The first argument to this method is the desired count of rows.
  771. The second argument is the number of rows to skip.
  772. </para>
  773. <example id="zend.db.select.building.limit.example">
  774. <title>Example of the limit() method</title>
  775. <programlisting role="php"><![CDATA[<?php
  776. // Build this query:
  777. // SELECT p."product_id", p."product_name"
  778. // FROM "products" AS p
  779. // LIMIT 10, 20
  780. $select = $db->select()
  781. ->from(array('p' => 'products'), array('product_id', 'product_name'))
  782. ->limit(10, 20);]]></programlisting>
  783. </example>
  784. <note>
  785. <para>
  786. The <code>LIMIT</code> syntax is not supported by all RDBMS
  787. brands. Some RDBMS require different syntax to support
  788. similar functionality. Each Zend_Db_Adapter_Abstract class
  789. includes a method to produce SQL appropriate for that RDBMS.
  790. </para>
  791. </note>
  792. <para>
  793. Use the <code>limitPage()</code> method for an alternative way
  794. to specify row count and offset. This method allows you to
  795. limit the result set to one of a series of fixed-length subsets
  796. of rows from the query's total result set. In other words, you
  797. specify the length of a "page" of results, and the ordinal
  798. number of the single page of results you want the query to return.
  799. The page number is the first argument of the
  800. <code>limitPage()</code> method, and the page length is the
  801. second argument. Both arguments are required; they have no
  802. default values.
  803. </para>
  804. <example id="zend.db.select.building.limit.example2">
  805. <title>Example of the limitPage() method</title>
  806. <programlisting role="php"><![CDATA[<?php
  807. // Build this query:
  808. // SELECT p."product_id", p."product_name"
  809. // FROM "products" AS p
  810. // LIMIT 10, 20
  811. $select = $db->select()
  812. ->from(array('p' => 'products'), array('product_id', 'product_name'))
  813. ->limitPage(2, 10);]]></programlisting>
  814. </example>
  815. </sect3>
  816. <sect3 id="zend.db.select.building.distinct">
  817. <title>Adding the DISTINCT Query Modifier</title>
  818. <para>
  819. The <code>distinct()</code> method enables you to add the
  820. <code>DISTINCT</code> keyword to your SQL query.
  821. </para>
  822. <example id="zend.db.select.building.distinct.example">
  823. <title>Example of the distinct() method</title>
  824. <programlisting role="php"><![CDATA[<?php
  825. // Build this query:
  826. // SELECT DISTINCT p."product_name"
  827. // FROM "products" AS p
  828. $select = $db->select()
  829. ->distinct()
  830. ->from(array('p' => 'products'), 'product_name');]]></programlisting>
  831. </example>
  832. </sect3>
  833. <sect3 id="zend.db.select.building.for-update">
  834. <title>Adding the FOR UPDATE Query Modifier</title>
  835. <para>
  836. The <code>forUpdate()</code> method enables you to add the
  837. <code>FOR UPDATE</code> modifier to your SQL query.
  838. </para>
  839. <example id="zend.db.select.building.for-update.example">
  840. <title>Example of forUpdate() method</title>
  841. <programlisting role="php"><![CDATA[<?php
  842. // Build this query:
  843. // SELECT FOR UPDATE p.*
  844. // FROM "products" AS p
  845. $select = $db->select()
  846. ->forUpdate()
  847. ->from(array('p' => 'products'));]]></programlisting>
  848. </example>
  849. </sect3>
  850. </sect2>
  851. <sect2 id="zend.db.select.execute">
  852. <title>Executing Select Queries</title>
  853. <para>
  854. This section describes how to execute the query represented by a
  855. Zend_Db_Select object.
  856. </para>
  857. <sect3 id="zend.db.select.execute.query-adapter">
  858. <title>Executing Select Queries from the Db Adapter</title>
  859. <para>
  860. You can execute the query represented by the Zend_Db_Select
  861. object by passing it as the first argument to the
  862. <code>query()</code> method of a Zend_Db_Adapter_Abstract
  863. object. Use the Zend_Db_Select objects instead of a string
  864. query.
  865. </para>
  866. <para>
  867. The <code>query()</code> method returns an object of type
  868. Zend_Db_Statement or PDOStatement, depending on the adapter type.
  869. </para>
  870. <example id="zend.db.select.execute.query-adapter.example">
  871. <title>Example using the Db adapter's query() method</title>
  872. <programlisting role="php"><![CDATA[<?php
  873. $select = $db->select()
  874. ->from('products');
  875. $stmt = $db->query($select);
  876. $result = $stmt->fetchAll();]]></programlisting>
  877. </example>
  878. </sect3>
  879. <sect3 id="zend.db.select.execute.query-select">
  880. <title>Executing Select Queries from the Object</title>
  881. <para>
  882. As an alternative to using the <code>query()</code> method
  883. of the adapter object, you can use the <code>query()</code>
  884. method of the Zend_Db_Select object.
  885. Both methods return an object of type Zend_Db_Statement or
  886. PDOStatement, depending on the adapter type.
  887. </para>
  888. <example id="zend.db.select.execute.query-select.example">
  889. <title>Example using the Select object's query method</title>
  890. <programlisting role="php"><![CDATA[<?php
  891. $select = $db->select()
  892. ->from('products');
  893. $stmt = $select->query();
  894. $result = $stmt->fetchAll();]]></programlisting>
  895. </example>
  896. </sect3>
  897. <sect3 id="zend.db.select.execute.tostring">
  898. <title>Converting a Select Object to a SQL String</title>
  899. <para>
  900. If you need access to a string representation of the SQL
  901. query corresponding to the Zend_Db_Select object, use
  902. the <code>__toString()</code> method.
  903. </para>
  904. <example id="zend.db.select.execute.tostring.example">
  905. <title>Example of the __toString() method</title>
  906. <programlisting role="php"><![CDATA[<?php
  907. $select = $db->select()
  908. ->from('products');
  909. $sql = $select->__toString();
  910. echo "$sql\n";
  911. // The output is the string:
  912. // SELECT * FROM "products"]]></programlisting>
  913. </example>
  914. </sect3>
  915. </sect2>
  916. <sect2 id="zend.db.select.other">
  917. <title>Other methods</title>
  918. <para>
  919. This section describes other methods of the Zend_Db_Select class
  920. that are not covered above: <code>getPart()</code> and
  921. <code>reset()</code>.
  922. </para>
  923. <sect3 id="zend.db.select.other.get-part">
  924. <title>Retrieving Parts of the Select Object</title>
  925. <para>
  926. The <code>getPart()</code> method returns a representation
  927. of one part of your SQL query. For example, you can use this
  928. method to return the array of expressions for the
  929. <code>WHERE</code> clause, or the array of columns
  930. (or column expressions) that are in the <code>SELECT</code>
  931. list, or the values of the count and offset for the
  932. <code>LIMIT</code> clause.
  933. </para>
  934. <para>
  935. The return value is not a string containing a fragment of SQL
  936. syntax. The return value is an internal representation, which
  937. is typically an array structure containing values and
  938. expressions. Each part of the query has a different structure.
  939. </para>
  940. <para>
  941. The single argument to the <code>getPart()</code> method is
  942. a string that identifies which part of the Select query to
  943. return. For example, the string <code>'from'</code>
  944. identifies the part of the Select object that stores
  945. information about the tables in the <code>FROM</code> clause,
  946. including joined tables.
  947. </para>
  948. <para>
  949. The Zend_Db_Select class defines constants you can use for
  950. parts of the SQL query. You can use these constant definitions,
  951. or you can the literal strings.
  952. </para>
  953. <table id="zend.db.select.other.get-part.table">
  954. <title>Constants used by getPart() and reset()</title>
  955. <tgroup cols="2">
  956. <thead>
  957. <row>
  958. <entry>Constant</entry>
  959. <entry>String value</entry>
  960. </row>
  961. </thead>
  962. <tbody>
  963. <row>
  964. <entry><code>Zend_Db_Select::DISTINCT</code></entry>
  965. <entry><code>'distinct'</code></entry>
  966. </row>
  967. <row>
  968. <entry><code>Zend_Db_Select::FOR_UPDATE</code></entry>
  969. <entry><code>'forupdate'</code></entry>
  970. </row>
  971. <row>
  972. <entry><code>Zend_Db_Select::COLUMNS</code></entry>
  973. <entry><code>'columns'</code></entry>
  974. </row>
  975. <row>
  976. <entry><code>Zend_Db_Select::FROM</code></entry>
  977. <entry><code>'from'</code></entry>
  978. </row>
  979. <row>
  980. <entry><code>Zend_Db_Select::WHERE</code></entry>
  981. <entry><code>'where'</code></entry>
  982. </row>
  983. <row>
  984. <entry><code>Zend_Db_Select::GROUP</code></entry>
  985. <entry><code>'group'</code></entry>
  986. </row>
  987. <row>
  988. <entry><code>Zend_Db_Select::HAVING</code></entry>
  989. <entry><code>'having'</code></entry>
  990. </row>
  991. <row>
  992. <entry><code>Zend_Db_Select::ORDER</code></entry>
  993. <entry><code>'order'</code></entry>
  994. </row>
  995. <row>
  996. <entry><code>Zend_Db_Select::LIMIT_COUNT</code></entry>
  997. <entry><code>'limitcount'</code></entry>
  998. </row>
  999. <row>
  1000. <entry><code>Zend_Db_Select::LIMIT_OFFSET</code></entry>
  1001. <entry><code>'limitoffset'</code></entry>
  1002. </row>
  1003. </tbody>
  1004. </tgroup>
  1005. </table>
  1006. <example id="zend.db.select.other.get-part.example">
  1007. <title>Example of the getPart() method</title>
  1008. <programlisting role="php"><![CDATA[<?php
  1009. $select = $db->select()
  1010. ->from('products')
  1011. ->order('product_id');
  1012. // You can use a string literal to specify the part
  1013. $orderData = $select->getPart( 'order' );
  1014. // You can use a constant to specify the same part
  1015. $orderData = $select->getPart( Zend_Db_Select::ORDER );
  1016. // The return value may be an array structure, not a string.
  1017. // Each part has a different structure.
  1018. print_r( $orderData );]]></programlisting>
  1019. </example>
  1020. </sect3>
  1021. <sect3 id="zend.db.select.other.reset">
  1022. <title>Resetting Parts of the Select Object</title>
  1023. <para>
  1024. The <code>reset()</code> method enables you to clear one
  1025. specified part of the SQL query, or else clear all parts of
  1026. the SQL query if you omit the argument.
  1027. </para>
  1028. <para>
  1029. The single argument is optional. You can specify the part
  1030. of the query to clear, using the same strings you used in
  1031. the argument to the <code>getPart()</code> method.
  1032. The part of the query you specify is reset to a default state.
  1033. </para>
  1034. <para>
  1035. If you omit the parameter, <code>reset()</code> changes all
  1036. parts of the query to their default state. This makes the
  1037. Zend_Db_Select object equivalent to a new object, as though you
  1038. had just instantiated it.
  1039. </para>
  1040. <example id="zend.db.select.other.reset.example">
  1041. <title>Example of the reset() method</title>
  1042. <programlisting role="php"><![CDATA[<?php
  1043. // Build this query:
  1044. // SELECT p.*
  1045. // FROM "products" AS p
  1046. // ORDER BY "product_name"
  1047. $select = $db->select()
  1048. ->from(array('p' => 'products')
  1049. ->order('product_name');
  1050. // Changed requirement, instead order by a different columns:
  1051. // SELECT p.*
  1052. // FROM "products" AS p
  1053. // ORDER BY "product_id"
  1054. // Clear one part so we can redefine it
  1055. $select->reset( Zend_Db_Select::ORDER );
  1056. // And specify a different column
  1057. $select->order('product_id');
  1058. // Clear all parts of the query
  1059. $select->reset();]]></programlisting>
  1060. </example>
  1061. </sect3>
  1062. </sect2>
  1063. </sect1>
  1064. <!--
  1065. vim:se ts=4 sw=4 et:
  1066. -->