sql >> Base de Datos >  >> RDS >> Mysql

Valor dinámico de Mysql como alias

¿Por qué estás usando la combinación izquierda en lugar de la combinación interna? Además, si está haciendo consultas dinámicas. Debería considerar el uso de procedimientos almacenados. Puede montar la instrucción SQL en una variable y luego ejecutar. He aquí un ejemplo rápido:

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.d.:Cuidado con los nombres que usas como alias. Pueden ser sintaxis SQL reservadas.