Mood Swing » Nostalgic

Journal » Post

pngfix
posted in: code at 07:20 pm
0 Reactions

I've learned something new today, and I thought I'd share it with you guys since it tooks me quite sometime to find the correct answer on google. My problem was I needed to select the same field in 1 table with a condition. Notice the table below, the rid column represents the person who referrer id which denotes who referred that person. So I needed to select all the name's along with the names of who referred them in 1 statement; e.g. felipe was referred by pedro.

+----+-----+--------+
| id | rid | name   |
+----+-----+--------+
|  1 |   0 | juan   |
|  2 |   5 | felipe |
|  3 |   1 | carlos |
|  4 |   0 | maria  |
|  5 |   0 | pedro  |
+----+-----+--------+

To make the long story short I used table aliases to reference the same table in 1 statement and a subselect to get the value i needed like so:

 
SELECT name

    (
SELECT t1.name FROM table1 t1 WHERE t2.rid t1.id) AS referrer 
    FROM table1 t2 WHERE rid 
0;
 
which gives us
+--------+----------+
| name   | referrer |
+--------+----------+
| felipe | pedro    |
| carlos | juan     |
+--------+----------+

It may seem trivial to most people but I hope this helps someone, I've been using PHP for quite some time but I have yet to get a good grip on my SQL, so for those who are like me you are not alone! ^^v

Talkback

No reactions

Post a reaction



 


*Enter the characters displayed on the image below on the verify image text box above. Note that this is case sensitive.

captcha image

 
Back to top
contact