joe
joe

Reputation: 103

Sqlite select query using result value from another select query from another table

I have checked the similar answer but didn't find what i am looking for.

I have a table from where I get a value like below:

SELECT value1 from table1;
b3 

I need to use this result for my next query:

SELECT b1,b2,b3,b4,b5,(SELECT value from table1) from table2;
15.26|13.14|11.08|9.05|7.05|b3
15.31|13.2|11.14|9.11|7.12|b3
15.37|13.26|11.2|9.18|7.18|b3
15.43|13.32|11.26|9.24|7.25|b3

the problem is that the SELECT statement is returning b3 instead of b3 values as per the following result (last column is return of b2 from the select)

SELECT b1,b2,b3,b4,b5,(SELECT value from table1) from table2;
15.26|13.14|11.08|9.05|7.05|11.08
15.31|13.2|11.14|9.11|7.12|11.14
15.37|13.26|11.2|9.18|7.18|11.2
15.43|13.32|11.26|9.24|7.25|11.26

any idea how to solve this? many thanks

Upvotes: 0

Views: 777

Answers (1)

forpas
forpas

Reputation: 164089

I suspect that you want a CASE expression:

SELECT b1,b2,b3,b4,b5,
  CASE (SELECT value from table1) 
    WHEN 'b1' THEN b1
    WHEN 'b2' THEN b2
    WHEN 'b3' THEN b3
    WHEN 'b4' THEN b4
    WHEN 'b5' THEN b5
  END result  
FROM table2

but this will work only if:

SELECT value from table1

returns only 1 row.
See the demo.
Results:

| b1    | b2    | b3    | b4   | b5   | result |
| ----- | ----- | ----- | ---- | ---- | ------ |
| 15.26 | 13.14 | 11.08 | 9.05 | 7.05 | 11.08  |
| 15.31 | 13.2  | 11.14 | 9.11 | 7.12 | 11.14  |
| 15.37 | 13.26 | 11.2  | 9.18 | 7.18 | 11.2   |
| 15.43 | 13.32 | 11.26 | 9.24 | 7.25 | 11.26  |

Upvotes: 1

Related Questions