我需要使用if子句从我的表中获取数据,这是我正在尝试做的一个例子;
select if (condition='example',
(/*query1(return more than one row)*/),
(/*query2(return more than one row)*/) as data from table1 where iduser='1'
我的完整查询:
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'
我的桌子;
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||
++========++======++ ++========++========++ ++========++=======++
概要
所以if bagian=dokter
,它会加入表格bsl_ruang
和mr_ranap_dokter
并获得ruper
和if bagian=perawat
,它会加入表格m_unit
和muser_tdinas
并获得nama
但if子句只能返回一个数据,还有其他方法吗?请注意,我无法更改我的数据库
答案 0 :(得分:1)
也许这不是最好的解决方案,但我决定使用一个程序解决我的问题,这是我的程序;
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;
我只需要在查询时调用它,希望它有所帮助