Kalle
Kalle

Reputation: 69

mysql select with IF or CASE and subquery

I have 2 tables: pf_rows

|  g1  |  g2  |  g3  |  g4  |
+------+------+------+------+
| foo1 | foo2 | foo3 | foo4 |
+------+------+------+------+

and pf_seq

| lite | qty |
+------+-----+
|  1   |  12 |
+------+-----+
|  2   |  12 |
+------+-----+

I need a query which returns values from pf_rows based value what resides in pf_seq. Like: when pf_seq.lite=1 then result be foo1 and when pf_seq.lite=2 then result be foo2 etc.

Upvotes: 0

Views: 81

Answers (1)

Stefano Zanini
Stefano Zanini

Reputation: 5926

If the two tables are not related, you will have to use a cross join

select  t2.lite,
        case
            when t2.lite = 1 then t1.g1
            when t2.lite = 2 then t1.g2
            /* other cases if needed */
            else null
        end as gx
from    pf_rows t1
cross join
        pf_seq t2

Note that this kind of query is not performing at all if the tables contain large amounts of rows.

Upvotes: 1

Related Questions