13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Retrieving Data from the Database<br />

259<br />

The same output, however, produced by this join query:<br />

select customerid, amount<br />

from orders<br />

order by amount desc<br />

limit 1;<br />

Because it relies on LIMIT, this query is not compatible with most RDBMSs, but it executes<br />

more efficiently on <strong>MySQL</strong> than the subquery version.<br />

One of the main reasons that <strong>MySQL</strong> did not get subqueries for so long was that<br />

there is very little that you cannot do without them.Technically, you can create a single,<br />

legal ANSI SQL query that has the same effect but relies on an inefficient, hack<br />

approach called the MAX-CONCAT trick.<br />

You can use subquery values in this way with all the normal comparison operators.<br />

Some special subquery comparison operators are also available, detailed in the next<br />

section.<br />

Subqueries <strong>and</strong> Operators<br />

There are five special subquery operators. Four are used with regular subqueries, <strong>and</strong> one<br />

(EXISTS) is usually used only with correlated subqueries <strong>and</strong> is covered in the next section.The<br />

four regular subquery operators are shown in Table 10.4.<br />

Table 10.4 Subquery Operators<br />

Name Sample Syntax Description<br />

ANY SELECT c1 FROM t1 Returns true if the comparison is<br />

WHERE c1 ><br />

true for any of the rows in the subquery.<br />

ANY (SELECT c1 FROM t2);<br />

IN SELECT c1 FROM t1 Equivalent to =ANY.<br />

WHERE c1 IN<br />

(SELECT c1 from t2);<br />

SOME SELECT c1 FROM t1 Alias for ANY; sometimes reads better<br />

WHERE c1 ><br />

to the human ear<br />

SOME (SELECT c1 FROM t2);!<br />

ALL SELECT c1 FROM t1 Returns true if the comparison is<br />

WHERE c1 ><br />

true for all of the rows in the subquery.<br />

ALL (SELECT c1 from t2);<br />

Each of these operators can appear only after a comparison operator, except for IN,<br />

which has its comparison operator (=) “rolled in,” so to speak.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!