У меня есть следующая хранимая процедура:
proc_main:begin
declare done tinyint unsigned default 0;
declare dpth smallint unsigned default 0;
create temporary table hier(
AGTREFERRER int unsigned,
AGTNO int unsigned,
depth smallint unsigned default 0
)engine = memory;
insert into hier values (p_agent_id, p_agent_id, dpth);
/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */
create temporary table tmp engine=memory select * from hier;
while done <> 1 do
if exists( select 1 from agents a inner join hier on a.AGTREFERRER = hier.AGTNO and hier.depth = dpth) then
insert into hier
select a.AGTREFERRER, a.AGTNO, dpth + 1 from agents a
inner join tmp on a.AGTREFERRER = tmp.AGTNO and tmp.depth = dpth;
set dpth = dpth + 1;
truncate table tmp;
insert into tmp select * from hier where depth = dpth;
else
set done = 1;
end if;
end while;
select
a.AGTNO,
a.AGTLNAME as agent_name,
if(a.AGTNO = b.AGTNO, null, b.AGTNO) as AGTREFERRER,
if(a.AGTNO = b.AGTNO, null, b.AGTLNAME) as parent_agent_name,
hier.depth,
a.AGTCOMMLVL
from
hier
inner join agents a on hier.AGTNO = a.AGTNO
inner join agents b on hier.AGTREFERRER = b.AGTNO
order by
-- dont want to sort by depth but by commission instead - i think ??
-- hier.depth, hier.agent_id;
a.AGTCOMMLVL desc;
drop temporary table if exists hier;
drop temporary table if exists tmp;
end proc_main
Хотя функция хорошо справляется со своей задачей - в настоящее время она позволяет сортировать только по убыванию в AGTCOMMLVL. Цель хранимой процедуры - сопоставить memberID с их parentID и связанным COMMLVL. После правильного сопряжения я использую memberID во втором запросе, чтобы получить информацию об этом конкретном члене.
Я бы хотел сортировать по любому количеству фильтров, но у меня есть следующие проблемы:
Я не могу найти способ передать переменную в хранимую процедуру, изменяя ее сортировку по полю.
Даже если бы я мог - на самом деле сортировка может содержать только данные из второго запроса (например, имя, фамилия и т. Д.)
Выполнение сортировки во втором запросе ничего не делает, даже если синтаксис правильный - он всегда возвращается к сортировке хранимой процедуры.
есть идеи?
EDIT
Мой php использует mysqli с кодом:
$sql = sprintf("call agent_hier2(%d)", $agtid);
$resulta = $mysqli->query($sql, MYSQLI_STORE_RESULT) or exit(mysqli_error($mysqli));