4

I'm selecting data from two different rows in the same table using a single sql.

"id"    "borrowMax" "holder"    "category"  "country"
"1"     "2"         "0"         "3"         "US"
"2"     "0"         "1"         "10"        "US"

What I'm trying to do works out to this.

select id, holder from mytable where id = 2
select borrowMax from mytable where id = (
        holder from the above select, in this case it's 1
) and category = 3

The way I do it after looking at examples online is

SELECT col1.id, col1.holder, col2.borrowMax
FROM collection_db col1
JOIN collection_db col2
ON col2.holder = col1.id
WHERE col1.id = 2 //Here, 2 is the value supplied by me
AND col2.category = 3

Sure, this works. But since it's something I pieced together myself, I have my doubts. How would you do something like this? Am I on the right track? (I'm sure I'm not).

3
  • looks ok to me - and if it gives you the results you want then it should be good. Commented Jun 21, 2013 at 16:55
  • @IanKenney I had doubts regarding the JOIN. Should it be INNER JOIN? Commented Jun 21, 2013 at 17:02
  • 1
    JOIN is OK: when you specify the ON ... condition, JOIN is equivalent to INNER JOIN. It's more or less explained here. Commented Jun 21, 2013 at 17:13

3 Answers 3

3

You can also use table alias for this.

select t1.id, t1.holder, t2.borrowMax from mytable t1, mytable t2 where t1.id = t2.holder
Sign up to request clarification or add additional context in comments.

Comments

1

I would make use of nested select statements for a use case like yours. There is no JOIN operation being used, just a select query over a already filtered set of results and a logically more coherent code.

SELECT borrowmax, holder, id FROM mytable WHERE 
  id = (SELECT holder FROM mytable WHERE id = 2 )
    AND category = 3

Comments

0

I had to find What is the difference in population between 2000 and 2010 in Indonesia? Table columns:

country STRING
population  NUMBER
year    NUMBER

This is the query that gave me the result I was looking for:

SELECT b.country,
(b.population - a.population) 
AS diff_population
  FROM population_years a
  JOIN population_years b ON b.country = a.country
WHERE b.country = 'Indonesia'
  AND a.year = 2000
  AND b.year = 2010;

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.