Hvorfor bruger du venstre sammenføjning i stedet for indre forbindelse? Også hvis du laver dynamiske forespørgsler. Du bør overveje at bruge Stored Procedures. Du kan montere SQL-sætningen i en variabel og derefter udføre. Her er et hurtigt eksempel:
CREATE DEFINER=`YourDBUSER`@`localhost` PROCEDURE `rtYourProcedureName`(IN variable1 int,variable2d varchar(100), sortBy varchar(50), startRow int, ThisSQL varchar(5000), OUT totalRows int)
BEGIN
###start: MySQL is dumb and do not allow default parameter values, set here:
SET @variable1 = IFNULL(variable1 ,'0');
SET @variable2 = IFNULL(variable2 ,'');
SET @sortBy = IFNULL(sortBy ,'');
SET @startRow = IFNULL(startRow ,1);
###end: MySQL is dumb and do not allow default parameter values
set @htwsql = ThisSQL;
set @htwsql = ' SELECT SQL_CALC_FOUND_ROWS STRAIGHT_JOIN t1.field1 ,t2.field2 ';
if @variable1 = 0 then
set @htwsql := concat(@htwsql, ' from table1 t1');
else
set @htwsql := concat(@htwsql,' from table2 t2 w INNER JOIN table1 t1 ');
end if;
set @htwsql := concat(@htwsql, ' where 1 = 1 ');
### sort order
if rtrim(ltrim(@sortBy)) <> '' then
set @htwsql := concat(@htwsql,char(13), ' ORDER BY ' , cast(@sortBy as char(50)));
end if;
### limit records for pagination
set @htwsql := concat(@htwsql,char(13), ' LIMIT ', StartRow-1 ,',',24);
### just to debug the generated SQL
insert into rtlogtmp (log) select concat ('rtYourProcedureName SQL = ',@htwsql);
PREPARE stmt1 FROM @htwsql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SELECT FOUND_ROWS() into totalRows;
END
p.s.:Vær forsigtig med de navne du bruger som alias. De kan være reserveret SQL-syntaks.