Jump to content

SQL - SELECT Question


Freid001

Recommended Posts

Hi, I'm not sure if this is possible and it might be a bit of a wired question but basically. Is there a away to select a column from a name stored in a row. 

 

So  for example: 

 

I have these to tables: 

 

TABLE 1

| ID | USER | Column Needed |

| 1  | Bob    | i2                        |

| 2  | Jim     | i4                        |

 

TABLE 2 

| i1 | i2 | i3 | i4 | i5|

| 0 |  9 | 1  | 0  | 2 |

 

And I want to select Bob and the column from TABLE 2 that is needed is i2.

 

I then also want to select Jim and the column from TABLE 2 that is needed is i4.

 

I want to do this all in one SQL query. And the column name that they need for each row is stores in TABLE 1 under column needed. 

 

Thanks for any help!!!! :)

 

 

Link to comment
https://forums.phpfreaks.com/topic/285693-sql-select-question/
Share on other sites

Yes I know its bad data base design. I originally created it ages ago when I didn't know too much about databases. And now I am kind of stuck with it. :(

 

I have 2 tables one stores all items available. The other stores how many of each item a user has. But it stores them via column hence the i1,i2, i3 .

Link to comment
https://forums.phpfreaks.com/topic/285693-sql-select-question/#findComment-1466651
Share on other sites

They should be like this

mysql> SELECT * FROM table_1;
+----+------+-----------+
| id | user | needed_id |
+----+------+-----------+
|  1 | Bob  |         2 |
|  2 | Jim  |         4 |
+----+------+-----------+

mysql> SELECT * FROM table_2;
+----+--------------+
| id | needed_value |
+----+--------------+
|  1 |            0 |
|  2 |            9 |
|  3 |            1 |
|  4 |            0 |
|  5 |            2 |
+----+--------------+

However, as you have it now, horrible db design calls for horrible queries

SELECT a.id, a.user, a.column_needed, b.val
FROM table_1 as a
    INNER JOIN 
    (
    SELECT 'i1' as id, i1 as val FROM table_2
    UNION
    SELECT 'i2', i2 FROM table_2
    UNION
    SELECT 'i3', i3 FROM table_2
    UNION
    SELECT 'i4', i4 FROM table_2
    UNION
    SELECT 'i5', i5 FROM table_2
    ) as b ON a.column_needed = b.id

+----+------+---------------+------+
| id | user | column_needed | val  |
+----+------+---------------+------+
|  1 | Bob  | i2            |    9 |
|  2 | Jim  | i4            |    0 |
+----+------+---------------+------+
Link to comment
https://forums.phpfreaks.com/topic/285693-sql-select-question/#findComment-1466663
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.