1

I`m trying to run a nested query on MySQL (phpmyadmin) and via PHP, and both result in the same output which is incorrect.

NOTE: Table name have been clipped due to sensitivity of project

SELECT * FROM `table1` WHERE ID="SELECT `field1` FROM `table2` WHERE ID=1"

This returns zero rows, although each query alone gives a valid output as below

SELECT `field1` FROM `table2` WHERE ID=1

Gives the required output, and this output when used in the first part of the main query provides also what is required. Please help.

1
  • 3
    Must be very sensitive if the table name alone can give it away. :) Commented Dec 20, 2011 at 21:03

2 Answers 2

5

Don't enclose it in quotes. Instead enclose it in parentheses:

SELECT * FROM `table1` WHERE ID=(SELECT `field1` FROM `table2` WHERE ID=1)

If multiple rows are expected from the subquery, use WHERE ID IN (SELECT...) instead of WHERE ID=(SELECT...)

You'll probably get better performance with a JOIN though:

SELECT table1.* 
FROM
  table1 JOIN table2 ON table1.ID = table2.field1
WHERE table1.ID = 1
Sign up to request clarification or add additional context in comments.

1 Comment

just figured it out :). Thanks. I'll mark as correct answer in two minutes (rules here)
2

Your nested query is wrong, it should look like this:

SELECT * FROM `table1` WHERE ID in (SELECT `field1` FROM `table2` WHERE ID=1)

In your case, you're comparing table1.ID with a string containing the second query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.