Reputation: 999
I need to get data from my table using if clause, here's an example of what I'm trying to do;
select if (condition='example',
(/*query1(return more than one row)*/),
(/*query2(return more than one row)*/) as data from table1 where iduser='1'
my complete query:
SELECT
if(bagian='DOKTER',
(SELECT b.ruper
from bsl_ruang b
join mr_ranap_dokter d
on (b.noregis=d.noregis)
where d.dokter = '999999'),
(SELECT u.nama
FROM m_unit u
join muser_tdinas t
on(t.unit=u.unit)
where id_user = '999999')) as ruper
FROM `muser` where id_user = '999999'
my tables;
bsl_ruang mr_ranap_dokter
++========++======++ ++========++========++
||noregis ||ruper || ||dokter ||noregis ||
++========++======++ ++========++========++
||10000000||ruper1|| ||9999999 ||10000000||
||10000001||ruper2|| ||9999999 ||10000001||
++========++======++ ++========++========++
m_unit muser_tdinas m_user
++========++======++ ++========++========++ ++========++=======++
||unit ||nama || ||id_user ||unit || ||id_user ||bagian ||
++========++======++ ++========++========++ ++========++=======++
||00001 ||ruper1|| ||8888888 ||00001 || ||9999999 ||DOKTER ||
||00002 ||ruper2|| ||8888888 ||00002 || ||8888888 ||PERAWAT||
++========++======++ ++========++========++ ++========++=======++
SUMMARY
so if bagian=dokter
, it will join table bsl_ruang
and mr_ranap_dokter
and get ruper
and if bagian=perawat
, it will join table m_unit
and muser_tdinas
and get nama
but if clause can only return one data, is there any other way to do this? note that I can't change my database
Upvotes: 0
Views: 76
Reputation: 999
maybe this is not the best solution but I decided to use a procedure for my problem, here's my procedure;
CREATE DEFINER=`root`@`%` PROCEDURE `GetRuperRanap`(lIdUser Varchar(12))
BEGIN
Declare lBagian VarChar(20);
SELECT bagian into lBagian FROM `muser` where id_user = lIdUser;
if lBagian='DOKTER' then
SELECT distinct b.ruper as ruper from bsl_ruang b join mr_ranap_dokter d on (b.noregis=d.noregis) where d.dokter = lIdUser;
else
SELECT u.nama as ruper FROM m_unit u join muser_tdinas t on(t.unit=u.unit) where id_user = lIdUser;
end if;
END;
and I just need to call it on query, hope it help
Upvotes: 1