php - MySQL: If a column value is 2 THEN do X ELSE do Y -
the database working on right messy. have 3 potential tables, want join in cases may 2 tables. let's call these table1, table2 , table3.
table1 has field called "type". if table1.type 2, need join table3. other values want join table2 , table3.
how can achieve in 1 single sql query rather than: 1) having 1 query select type. 2) make php foreach-loop check type of current iteration , 3) perform new query according type value.
edit: i'll try more specific.
table1 has column named "pid" references whole other table, that's redundant question. tried working ways around unions , left joins couldn't manage achieve looking for.
i want select results database "pid" value being "100". gives me 4 rows in return, 2 of them of type value "2" , others "1".
so want achieve following 2 sql statements in one:
(if "type" "2")
select * table1 t1 inner join table3 t3 on t1.id = t3.t1_id t1.pid = 100
(if "type" not "2")
select * table1 t1 inner join table2 t2 on t1.id = t2.t1_id inner join table3 t3 on t2.id = t3.t2_id t1.pid = 100
i'm guessing manage union statement, i'm confused on how implement t1.pid = '100' part.
use union e.g.
select t1.*, t3.* table1 t1 inner join table3 t3 on t1.id = t3.t1_id t1.pid = 100 , t1.type = 2 union select t1.*, t3.* table1 t1 inner join table2 t2 on t1.id = t2.t1_id inner join table3 t3 on t2.id = t3.t2_id t1.pid = 100 , t1.type <> 2;
but better explicitly name columns want back.
Comments
Post a Comment