TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
 
 
LinkBack Thread Tools Search this Thread Display Modes
Prev Previous Post   Next Post Next
Old 09-07-2007, 10:27 AM   #1 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Red face The art of sub-selects

Sub-Selects are one of the most powerful new(ish) additions to the mysql database. They are supported from mysql 4.1 onward.

Code:
SET @v1 = '';
SELECT @v1:=column_id FROM table1 WHERE column='blah';
SELECT * FROM table2 WHERE column2 = @v1;
Now while thats all well and good, its not very practical, long and doesnt look very nice. Now lets take doing the same thing with a mysql sub-select!

Code:
SELECT * FROM table2 WHERE column2 = (SELECT column_id FROM table1 WHERE column='blah' LIMIT 1);
See how easy that is!

Now for some more advanced stuff:

Using a sub-select query as a table:
Code:
SELECT 
     table1.id, 
     tbl2.example 
FROM 
     table1, 
     (SELECT * FROM table2 WHERE id=1) tbl2
WHERE
     table1.referance = table2.referance
The query above, uses a query result set to create a temporary table in mysql, you can then browse this table using normal functions, extremely handy in some cases.

Using Sub-select in an "IN" where statement:
Code:
SELECT
     column
FROM
     table1
WHERE
     table1.ref_id IN (SELECT id FROM table2)
The subselect query in this case acts as if you were adding a list to the IN, ie:
Code:
table1.ref_id IN (1,2,3,4,5,6,7,8,9,10)

Last edited by bluesaga : 09-07-2007 at 02:23 PM.
bluesaga is offline  
Reply With Quote
 



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 03:49 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design