473,387 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

sub-query question


How does one embed a sub-query lookup to one table in order to
replace a foreign key id number with it's name in a SELECT on a
second table?

i.e.: given the following two tables, I want to replace the color_id
of 1
with the color_name 'red.' (The SQL to create the two tables follows
below.)

test=# SELECT * from users ;
color_id | name | the_date
----------+------+------------
1 | john | 2004-03-10
3 | jane | 2004-04-12
1 | joe | 2004-05-14
2 | jepe | 2004-06-16
(4 rows)

test=# SELECT * from colors;
color_id | color_name
----------+------------
1 | red
2 | green
3 | blue
(3 rows)
My attempts yield an 'f' which looks suspiciously like a boolean false.
Is there an ordering issue with my sub-query, such that the sub-query
doesn't have enough info to perform its lookup?

Here's my query:

SELECT (
u.color_id = (
SELECT c.color_name
FROM colors c
WHERE color_id = 1)) AS color_name,
u.name, u.the_date
FROM users u
WHERE u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;

It returns:

color_name | name | the_date
------------+------+------------
f | joe | 2004-05-14
(1 row)
Thanks!
Scott
Here's the SQL to create my test tables:

CREATE TABLE colors (color_id SERIAL PRIMARY KEY, color_name text);
CREATE TABLE users (color_id integer REFERENCES colors, name text,
the_date date);

INSERT INTO colors (color_name) VALUES ('red');
INSERT INTO colors (color_name) VALUES ('green');
INSERT INTO colors (color_name) VALUES ('blue');

INSERT INTO users (color_id, name, the_date) VALUES (1, 'john',
'2004-03-10');
INSERT INTO users (color_id, name, the_date) VALUES (3, 'jane',
'2004-04-12');
INSERT INTO users (color_id, name, the_date) VALUES (1, 'joe',
'2004-05-14');
INSERT INTO users (color_id, name, the_date) VALUES (2, 'jepe',
'2004-06-16');

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #1
5 2517
something == otherthing is a boolean expression, you are asking the
database to compare both values, u.color_id is not equal c.color_name,
that's why you get 'f'.

I guess that you want to replace the color_id from users by the
corresponding color_name from colors:

SELECT
c.color_name, u.name, u.the_date
FROM
users u
INNER JOIN colors c ON (u.color_id=c.color_id)
WHERE
u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;
If you were trying to do another thing, I'm sorry, I didn't get it :(

Scott Frankel wrote:

How does one embed a sub-query lookup to one table in order to
replace a foreign key id number with it's name in a SELECT on a
second table?

i.e.: given the following two tables, I want to replace the color_id
of 1
with the color_name 'red.' (The SQL to create the two tables follows
below.)

test=# SELECT * from users ;
color_id | name | the_date
----------+------+------------
1 | john | 2004-03-10
3 | jane | 2004-04-12
1 | joe | 2004-05-14
2 | jepe | 2004-06-16
(4 rows)

test=# SELECT * from colors;
color_id | color_name
----------+------------
1 | red
2 | green
3 | blue
(3 rows)
My attempts yield an 'f' which looks suspiciously like a boolean false.
Is there an ordering issue with my sub-query, such that the sub-query
doesn't have enough info to perform its lookup?

Here's my query:

SELECT (
u.color_id = (
SELECT c.color_name
FROM colors c
WHERE color_id = 1)) AS color_name,
u.name, u.the_date
FROM users u
WHERE u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;

It returns:

color_name | name | the_date
------------+------+------------
f | joe | 2004-05-14
(1 row)
Thanks!
Scott
Here's the SQL to create my test tables:

CREATE TABLE colors (color_id SERIAL PRIMARY KEY, color_name text);
CREATE TABLE users (color_id integer REFERENCES colors, name text,
the_date date);

INSERT INTO colors (color_name) VALUES ('red');
INSERT INTO colors (color_name) VALUES ('green');
INSERT INTO colors (color_name) VALUES ('blue');

INSERT INTO users (color_id, name, the_date) VALUES (1, 'john',
'2004-03-10');
INSERT INTO users (color_id, name, the_date) VALUES (3, 'jane',
'2004-04-12');
INSERT INTO users (color_id, name, the_date) VALUES (1, 'joe',
'2004-05-14');
INSERT INTO users (color_id, name, the_date) VALUES (2, 'jepe',
'2004-06-16');

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #2
Scott Frankel <le*****@pacbell.net> writes:
Here's my query: SELECT (
u.color_id = (
SELECT c.color_name
FROM colors c
WHERE color_id = 1)) AS color_name,
u.name, u.the_date
FROM users u
WHERE u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;


I think you want

SELECT
(SELECT c.color_name
FROM colors c
WHERE color_id = u.color_id) AS color_name,
u.name, u.the_date
FROM users u
WHERE u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;

The sub-select can refer to a variable of the outer query, as long
as you are careful to qualify it so it can't be mistaken for a variable
of the sub-select itself.

You could also express this query as a join. If you are pulling a whole
lot of users rows, the join way would probably be more efficient.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to ma*******@postgresql.org)

Nov 23 '05 #3
On Fri, Nov 12, 2004 at 09:52:09AM -0800, Scott Frankel wrote:

How does one embed a sub-query lookup to one table in order to
replace a foreign key id number with it's name in a SELECT on a
second table?
You're talking about joins.

http://www.postgresql.org/docs/7.4/s...rial-join.html
http://www.postgresql.org/docs/7.4/s...pressions.html
i.e.: given the following two tables, I want to replace the color_id
of 1
with the color_name 'red.' (The SQL to create the two tables follows
below.)

test=# SELECT * from users ;
color_id | name | the_date
----------+------+------------
1 | john | 2004-03-10
3 | jane | 2004-04-12
1 | joe | 2004-05-14
2 | jepe | 2004-06-16

test=# SELECT * from colors;
color_id | color_name
----------+------------
1 | red
2 | green
3 | blue


There are at least four ways to write the join query you want:

SELECT color_name, name, the_date
FROM users NATURAL JOIN colors;

SELECT color_name, name, the_date
FROM users JOIN colors USING (color_id);

SELECT color_name, name, the_date
FROM users JOIN colors ON colors.color_id = users.color_id;

SELECT color_name, name, the_date
FROM users, colors
WHERE users.color_id = colors.color_id;

Debate exists about which of the above is "better." I tend to use
the second and third forms because I think they most clearly document
how the tables are joined, and because I think of the WHERE clause
as meaning "...and here are the records I want from all that."

Of course that's just my opinion. I could be wrong.
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #4
On Fri, Nov 12, 2004 at 11:26:14AM -0700, Michael Fuhr wrote:
There are at least four ways to write the join query you want:


I may have misunderstood what results you're looking for, but the
examples I gave may nevertheless be useful. Sorry if they cause
any confusion.

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postgresql.org

Nov 23 '05 #5

Cooking with gas once again ;) Thanks for the info on JOINs!
Scott


On Nov 12, 2004, at 9:52 AM, Scott Frankel wrote:

How does one embed a sub-query lookup to one table in order to
replace a foreign key id number with it's name in a SELECT on a
second table?

i.e.: given the following two tables, I want to replace the color_id
of 1
with the color_name 'red.' (The SQL to create the two tables follows
below.)

test=# SELECT * from users ;
color_id | name | the_date
----------+------+------------
1 | john | 2004-03-10
3 | jane | 2004-04-12
1 | joe | 2004-05-14
2 | jepe | 2004-06-16
(4 rows)

test=# SELECT * from colors;
color_id | color_name
----------+------------
1 | red
2 | green
3 | blue
(3 rows)
My attempts yield an 'f' which looks suspiciously like a boolean false.
Is there an ordering issue with my sub-query, such that the sub-query
doesn't have enough info to perform its lookup?

Here's my query:

SELECT (
u.color_id = (
SELECT c.color_name
FROM colors c
WHERE color_id = 1)) AS color_name,
u.name, u.the_date
FROM users u
WHERE u.color_id = 1
ORDER BY u.the_date DESC LIMIT 1;

It returns:

color_name | name | the_date
------------+------+------------
f | joe | 2004-05-14
(1 row)
Thanks!
Scott
Here's the SQL to create my test tables:

CREATE TABLE colors (color_id SERIAL PRIMARY KEY, color_name text);
CREATE TABLE users (color_id integer REFERENCES colors, name text,
the_date date);

INSERT INTO colors (color_name) VALUES ('red');
INSERT INTO colors (color_name) VALUES ('green');
INSERT INTO colors (color_name) VALUES ('blue');

INSERT INTO users (color_id, name, the_date) VALUES (1, 'john',
'2004-03-10');
INSERT INTO users (color_id, name, the_date) VALUES (3, 'jane',
'2004-04-12');
INSERT INTO users (color_id, name, the_date) VALUES (1, 'joe',
'2004-05-14');
INSERT INTO users (color_id, name, the_date) VALUES (2, 'jepe',
'2004-06-16');

---------------------------(end of
broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: tshad | last post by:
I have an example I copied from "programming asp.net" (o'reilly) and can't seem to get the Sub (writefile) to execute. It displays all the response.write lines that are called directly, but not...
5
by: Colleyville Alan | last post by:
I have a sub that can do two different tasks based on the value of one variable. So I'd like to have two different buttons on the same form run this, but each one setting a flag so that the...
10
by: tmaster | last post by:
When I try to dynamically add a second sub menu item to this ContextMenu item, I get an error 'Specified argument was out of the range of valid values'. Private Sub mnuTopics_Show_Select(ByVal...
8
by: koorb | last post by:
I am starting a program from a module with the Sub main procedure and I want it to display two forms for the program's interface, but when I run the program both forms just open and then program...
12
by: Ron | last post by:
Greetings, I am trying to understand the rational for Raising Events instead of just calling a sub. Could someone explain the difference between the following 2 scenarios? Why would I want to...
4
by: dbuchanan | last post by:
Is the following behavior normal? Both the 'Protected sub' in the inherited form and the 'Private Shadows sub' in the derived form fires. My interpretation of MSDN help on the topic "Shadows"...
4
by: excelleinc.com | last post by:
Hello, I'm trying to put sub that's shared between all forms in my app in module so when I make change I just change it one time. This sub should execute and then invoke sub defaults() that's...
20
by: vitorjol | last post by:
Hello. I have 2 forms (Form1 and Form2). When i call the Sub placed in form1 from form2, i get the error "object reference not set to an instance of an object" ! What can i do to solve the...
6
by: Greg Strong | last post by:
Hello All, Is is possible to use an ADO recordset to populate an unbound continuous Subform? I've done some Googling without much luck, so this maybe impossible, but let me try to explain...
1
by: YotamElal | last post by:
Hello, I have a popup problem. When a popup is opened, I want all other popups to close immediatly. (except for its self and it's child popups) Here is my code: code: <!DOCTYPE HTML PUBLIC...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.