| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483 |
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- Reviewed: no -->
- <sect1 id="zend.db.select">
- <title>Zend_Db_Select</title>
- <sect2 id="zend.db.select.introduction">
- <title>Introduction</title>
- <para>
- The <classname>Zend_Db_Select</classname> object represents a SQL <code>SELECT</code>
- query statement. The class has methods for adding individual parts to the query. You can
- specify some parts of the query using PHP methods and data structures, and the class
- forms the correct SQL syntax for you. After you build a query, you can execute the query
- as if you had written it as a string.
- </para>
- <para>
- The value offered by <classname>Zend_Db_Select</classname> includes:
- </para>
- <itemizedlist>
- <listitem>
- <para>
- Object-oriented methods for specifying SQL queries in a piece-by-piece manner;
- </para>
- </listitem>
- <listitem>
- <para>
- Database-independent abstraction of some parts of the SQL query;
- </para>
- </listitem>
- <listitem>
- <para>
- Automatic quoting of metadata identifiers in most cases, to support identifiers
- containing SQL reserved words and special characters;
- </para>
- </listitem>
- <listitem>
- <para>
- Quoting identifiers and values, to help reduce risk of SQL injection attacks.
- </para>
- </listitem>
- </itemizedlist>
- <para>
- Using <classname>Zend_Db_Select</classname> is not mandatory. For very simple SELECT
- queries, it is usually simpler to specify the entire SQL query as a string and execute
- it using Adapter methods like <code>query()</code> or <code>fetchAll()</code>. Using
- <classname>Zend_Db_Select</classname> is helpful if you need to assemble a SELECT query
- procedurally, or based on conditional logic in your application.
- </para>
- </sect2>
- <sect2 id="zend.db.select.creating">
- <title>Creating a Select Object</title>
- <para>
- You can create an instance of a <classname>Zend_Db_Select</classname> object using the
- <code>select()</code> method of a <classname>Zend_Db_Adapter_Abstract</classname>
- object.
- </para>
- <example id="zend.db.select.creating.example-db">
- <title>Example of the database adapter's select() method</title>
- <programlisting language="php"><![CDATA[
- $db = Zend_Db::factory( ...options... );
- $select = $db->select();
- ]]></programlisting>
- </example>
- <para>
- Another way to create a <classname>Zend_Db_Select</classname> object is with its
- constructor, specifying the database adapter as an argument.
- </para>
- <example id="zend.db.select.creating.example-new">
- <title>Example of creating a new Select object</title>
- <programlisting language="php"><![CDATA[
- $db = Zend_Db::factory( ...options... );
- $select = new Zend_Db_Select($db);
- ]]></programlisting>
- </example>
- </sect2>
- <sect2 id="zend.db.select.building">
- <title>Building Select queries</title>
- <para>
- When building the query, you can add clauses of the query one by one. There is a
- separate method to add each clause to the <classname>Zend_Db_Select</classname> object.
- </para>
- <example id="zend.db.select.building.example">
- <title>Example of the using methods to add clauses</title>
- <programlisting language="php"><![CDATA[
- // 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>
- You also can use most methods of the <classname>Zend_Db_Select</classname> object with a
- convenient fluent interface. A fluent interface means that each method returns a
- reference to the object on which it was called, so you can immediately call another
- method.
- </para>
- <example id="zend.db.select.building.example-fluent">
- <title>Example of the using the fluent interface</title>
- <programlisting language="php"><![CDATA[
- $select = $db->select()
- ->from( ...specify table and columns... )
- ->where( ...specify search criteria... )
- ->order( ...specify sorting criteria... );
- ]]></programlisting>
- </example>
- <para>
- The examples in this section show usage of the fluent interface, but you can use the
- non-fluent interface in all cases. It is often necessary to use the non-fluent
- interface, for example, if your application needs to perform some logic before adding a
- clause to a query.
- </para>
- <sect3 id="zend.db.select.building.from">
- <title>Adding a FROM clause</title>
- <para>
- Specify the table for this query using the <code>from()</code> method. You can
- specify the table name as a simple string. <classname>Zend_Db_Select</classname>
- applies identifier quoting around the table name, so you can use special characters.
- </para>
- <example id="zend.db.select.building.from.example">
- <title>Example of the from() method</title>
- <programlisting language="php"><![CDATA[
- // 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,
- <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // Build this query:
- // SELECT p.*
- // FROM "products" AS p
- $select = $db->select()
- ->from( array('p' => 'products') );
- ]]></programlisting>
- </example>
- <para>
- Some RDBMS brands support a leading schema specifier for a table. You can specify
- the table name as "<code>schemaName.tableName</code>", where
- <classname>Zend_Db_Select</classname> quotes each part individually, or you may
- specify the schema name separately. A schema name specified in the table name takes
- precedence over a schema provided separately in the event that both are provided.
- </para>
- <example id="zend.db.select.building.from.example-schema">
- <title>Example of specifying a schema name</title>
- <programlisting language="php"><![CDATA[
- // 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>Adding Columns</title>
- <para>
- In the second argument of the <code>from()</code> method, you can specify the
- columns to select from the respective table. If you specify no columns, the default
- is "<code>*</code>", the SQL wildcard for "all columns".
- </para>
- <para>
- You can list the columns in a simple array of strings, or as an associative mapping
- of column alias to column name. If you only have one column to query, and you don't
- need to specify a column alias, you can list it as a plain string instead of an
- array.
- </para>
- <para>
- If you give an empty array as the columns argument, no columns from the respective
- table are included in the result set. See a
- <link linkend="zend.db.select.building.join.example-no-columns">code example</link>
- under the section on the <code>join()</code> method.
- </para>
- <para>
- You can specify the column name as "<code>correlationName.columnName</code>".
- <classname>Zend_Db_Select</classname> quotes each part individually. If you don't
- specify a correlation name for a column, it uses the correlation name for the table
- named in the current <code>from()</code> method.
- </para>
- <example id="zend.db.select.building.columns.example">
- <title>Examples of specifying columns</title>
- <programlisting language="php"><![CDATA[
- // 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>Adding Expression Columns</title>
- <para>
- Columns in SQL queries are sometimes expressions, not simply column names from a
- table. Expressions should not have correlation names or quoting applied. If your
- column string contains parentheses, <classname>Zend_Db_Select</classname> recognizes
- it as an expression.
- </para>
- <para>
- You also can create an object of type <classname>Zend_Db_Expr</classname>
- explicitly, to prevent a string from being treated as a column name.
- <classname>Zend_Db_Expr</classname> is a minimal class that contains a single
- string. <classname>Zend_Db_Select</classname> recognizes objects of type
- <classname>Zend_Db_Expr</classname> and converts them back to string, but does not
- apply any alterations, such as quoting or correlation names.
- </para>
- <note>
- <para>
- Using <classname>Zend_Db_Expr</classname> for column names is not necessary if
- your column expression contains parentheses;
- <classname>Zend_Db_Select</classname> recognizes parentheses and treats the
- string as an expression, skipping quoting and correlation names.
- </para>
- </note>
- <example id="zend.db.select.building.columns-expr.example">
- <title>Examples of specifying columns containing expressions</title>
- <programlisting language="php"><![CDATA[
- // 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>
- In the cases above, <classname>Zend_Db_Select</classname> does not alter the string
- to apply correlation names or identifier quoting. If those changes are necessary to
- resolve ambiguity, you must make the changes manually in the string.
- </para>
- <para>
- If your column names are SQL keywords or contain special characters, you should use
- the Adapter's <code>quoteIdentifier()</code> method and interpolate the result into
- the string. The <code>quoteIdentifier()</code> method uses SQL quoting to delimit
- the identifier, which makes it clear that it is an identifier for a table or a
- column, and not any other part of SQL syntax.
- </para>
- <para>
- Your code is more database-independent if you use the
- <code>quoteIdentifier()</code> method instead of typing quotes literally in your
- string, because some RDBMS brands use nonstandard symbols for quoting identifiers.
- The <code>quoteIdentifier()</code> method is designed to use the appropriate
- quoting symbols based on the adapter type. The <code>quoteIdentifier()</code>
- method also escapes any quote characters that appear within the identifier name
- itself.
- </para>
- <example id="zend.db.select.building.columns-quoteid.example">
- <title>Examples of quoting columns in an expression</title>
- <programlisting language="php"><![CDATA[
- // Build this query,
- // quoting the 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.columns-atomic">
- <title>Adding columns to an existing FROM or JOIN table</title>
- <para>
- There may be cases where you wish to add columns to an existing FROM or JOIN table
- after those methods have been called. The <code>columns()</code> method allows you
- to add specific columns at any point before the query is executed. You can supply
- the columns as either a string or <classname>Zend_Db_Expr</classname> or as an array
- of these elements. The second argument to this method can be omitted, implying that
- the columns are to be added to the FROM table, otherwise an existing correlation
- name must be used.
- </para>
- <example id="zend.db.select.building.columns-atomic.example">
- <title>Examples of adding columns with the columns() method</title>
- <programlisting language="php"><![CDATA[
- // Build this query:
- // SELECT p."product_id", p."product_name"
- // FROM "products" AS p
- $select = $db->select()
- ->from(array('p' => 'products'), 'product_id')
- ->columns('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'), 'p.product_id')
- ->columns('product_name', 'p');
- // Alternatively use columns('p.product_name')
- ]]></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 <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // 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 <classname>Zend_Db_Expr</classname> 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 language="php"><![CDATA[
- // 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 <classname>Zend_Db_Select</classname>.
- </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>
- <para>
- In addition to these join methods, you can simplify your queries by using the
- JoinUsing methods. Instead of supplying a full condition to your join, you simply
- pass the column name on which to join and the <classname>Zend_Db_Select</classname>
- object completes the condition for you.
- </para>
- <example id="zend.db.select.building.joinusing.example">
- <title>Example of the joinUsing() method</title>
- <programlisting language="php"><![CDATA[
- // Build this query:
- // SELECT *
- // FROM "table1"
- // JOIN "table2"
- // ON "table1".column1 = "table2".column1
- // WHERE column2 = 'foo'
- $select = $db->select()
- ->from('table1')
- ->joinUsing('table2', 'column1')
- ->where('column2 = ?', 'foo');
- ]]></programlisting>
- </example>
- <para>
- Each of the applicable join methods in the <classname>Zend_Db_Select</classname>
- component has a corresponding 'using' method.
- </para>
- <itemizedlist>
- <listitem>
- <para>
- <code>joinUsing(table, join, [columns])</code> and
- <code>joinInnerUsing(table, join, [columns])</code>
- </para>
- </listitem>
- <listitem>
- <para>
- <code>joinLeftUsing(table, join, [columns])</code>
- </para>
- </listitem>
- <listitem>
- <para>
- <code>joinRightUsing(table, join, [columns])</code>
- </para>
- </listitem>
- <listitem>
- <para>
- <code>joinFullUsing(table, join, [columns])</code>
- </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 language="php"><![CDATA[
- // 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. <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // 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
- <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // 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 language="php"><![CDATA[
- // 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>
- <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // 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>.
- <classname>Zend_Db_Select</classname> 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 <classname>Zend_Db_Select</classname>, 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 language="php"><![CDATA[
- // 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
- <classname>Zend_Db_Expr</classname>.
- </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 <classname>Zend_Db_Select</classname>, 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 language="php"><![CDATA[
- // 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 <classname>Zend_Db_Select</classname>, 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 <classname>Zend_Db_Expr</classname>.
- </para>
- <example id="zend.db.select.building.order.example">
- <title>Example of the order() method</title>
- <programlisting language="php"><![CDATA[
- // 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 <classname>Zend_Db_Select</classname>, 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 language="php"><![CDATA[
- // 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
- <classname>Zend_Db_Adapter_Abstract</classname> 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 language="php"><![CDATA[
- // 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 language="php"><![CDATA[
- // 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 language="php"><![CDATA[
- // 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
- <classname>Zend_Db_Select</classname> 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 <classname>Zend_Db_Select</classname>
- object by passing it as the first argument to the <code>query()</code> method of a
- <classname>Zend_Db_Adapter_Abstract</classname> object. Use the
- <classname>Zend_Db_Select</classname> objects instead of a string query.
- </para>
- <para>
- The <code>query()</code> method returns an object of type
- <classname>Zend_Db_Statement</classname> 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 language="php"><![CDATA[
- $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
- <classname>Zend_Db_Select</classname> object. Both methods return an object of type
- <classname>Zend_Db_Statement</classname> 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 language="php"><![CDATA[
- $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
- <classname>Zend_Db_Select</classname> object, use the <code>__toString()</code>
- method.
- </para>
- <example id="zend.db.select.execute.tostring.example">
- <title>Example of the __toString() method</title>
- <programlisting language="php"><![CDATA[
- $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 <classname>Zend_Db_Select</classname> 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 <classname>Zend_Db_Select</classname> 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><classname>Zend_Db_Select::DISTINCT</classname></entry>
- <entry><code>'distinct'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::FOR_UPDATE</classname></entry>
- <entry><code>'forupdate'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::COLUMNS</classname></entry>
- <entry><code>'columns'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::FROM</classname></entry>
- <entry><code>'from'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::WHERE</classname></entry>
- <entry><code>'where'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::GROUP</classname></entry>
- <entry><code>'group'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::HAVING</classname></entry>
- <entry><code>'having'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::ORDER</classname></entry>
- <entry><code>'order'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::LIMIT_COUNT</classname></entry>
- <entry><code>'limitcount'</code></entry>
- </row>
- <row>
- <entry><classname>Zend_Db_Select::LIMIT_OFFSET</classname></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 language="php"><![CDATA[
- $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 <classname>Zend_Db_Select</classname> 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 language="php"><![CDATA[
- // 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:
- -->
|