using a variable mysql not working as expected? - mysql

It doesn't like the limit line below. How would I use the variable #row in this case to limit the result set?
SELECT #row := 5;
SELECT * FROM MyTable
limit #row
Error:
Unexpected '#row'

The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants https://dev.mysql.com/doc/refman/8.0/en/select.html
So,
SELECT * FROM MyTable
limit 5

You could use a prepared statement...
SET #row = 5;
SET #s = CONCAT('SELECT * FROM MyTable LIMIT ', #row);
PREPARE stmt FROM #s;
EXECUTE stmt;

Related

select * from t limit #var

I am using multi-value option on grafana to select metrics and display them dynamically, this method works on graphs fine because I am not putting any limiter but I want to use Gauge to display the last entered data and the selected options to show the desired metric like this
.
And here i am stuck.
here is things i tried but naah didn't work,;
I tried to create a procedure for test;
CREATE PROCEDURE getData()
BEGIN
SET #itemlimit := JSON_LENGTH(JSON_ARRAY('conductivite0','conductivite1'));
SELECT UNIX_TIMESTAMP(datetime) as time_sec,
value as value,
label as metric
FROM valeur_capteur_SD
WHERE label in ('conductivite0','conductivite1')
ORDER BY id DESC LIMIT 0, #itemlimit;
END //
DELIMITER ;
and using a variable,
SET #var =
(
SELECT vars
FROM (
SELECT
JSON_LENGTH(
REPLACE(
CONCAT("[", "'conductivite0','conductivite1'", "]"),"'",'"'
)
) 'vars') as vars
);
SELECT
UNIX_TIMESTAMP(datetime) as time_sec,
value as value,
label as metric
FROM valeur_capteur_SD
WHERE label in ('conductivite0','conductivite1','debit0')
ORDER BY id DESC
LIMIT #var;
Well, after struggling for hours i found out a way to deal with it
DELIMITER //
CREATE PROCEDURE `getSelectedSensors`(IN param TEXT)
BEGIN
SET #query1 := CONCAT("
SELECT UNIX_TIMESTAMP(datetime) as time_sec,value as value, label as metric
FROM valeur_capteur_SD WHERE label in (",param,")
ORDER BY id DESC
LIMIT 0, ?");
PREPARE stmt1 FROM #query1;
SET #itemlimit = (LENGTH(param) - LENGTH(REPLACE(param, ',', ''))) +1;
EXECUTE stmt1 USING #itemlimit;
DEALLOCATE PREPARE stmt1;
END;

Table name as field

Is it possible to query a table whose name comes from a sub-query?
For example.,
SELECT * FROM <TABLE_NAME IS <SUB_QUERY>>
select * from (
(select distinct(name) from category where id = 3 limit 1) CAT);
INNER QUERY RESULTS --> DEPARTMENT;
So it has to fetch from department table.
Using Mysql as DB.
You should use Prepared Statements.
In your case it should be:
select #name := name from (
(select distinct(name) from category where id = 3 limit 1) CAT);
set #sqlquery := 'select * from ' . #name ;
prepare qry from #sqlquery ;
execute qry;
deallocate prepare qry;
This might be helpful SQL Syntax for Prepared Statements
In two words: you can execute sql commands specified in varchar variables which can be produced by concatenation and other stuff.

MySQL Variable not working

I tried to learn about MySQL Variable and do command like this
SET #target=`name`;
SELECT #target FROM transaction_product LIMIT 10;
But it is error and said Unknown column 'name' in 'field list'
Why it is error, i'm sure there is column name on my field list
here is the screenshot of the table
you need to use different quotes 'name' for assigning string to a variable and `name` for column names:
SET #target='name';
to get column value you can use INTO clause:
SELECT `name`
INTO #target
FROM transaction_product
LIMIT 1;
to get multiple rows in single variables you can use GROUP_CONCAT:
SELECT GROUP_CONCAT(`name`)
INTO #target
FROM transaction_product
LIMIT 10;
to execute query dynamically:
SET #target='`name`';
SET #query1 = CONCAT('
SELECT ',#target,'
FROM transaction_product
LIMIT 10'
);
PREPARE stmt FROM #query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT #target:=`name` FROM transaction_product LIMIT 10;

MySQL: alias column name question

Is it possible to alias a column name with the result of a simple SELECT query.
This doesn't work:
SELECT `hlevel1` AS (SELECT `level1` FROM `hierarchy_labels` LIMIT 1) FROM `hierarchy`;
Any Suggestions?
You can't do this.
Aliases are used to rename a field or to name a calculated field.
If you simply want your results to be named 'hlevel1', you may want to try this:
SELECT level1 as hlevel1 FROM hierarchy_labels LIMIT 1
Use a prepared statement.
SELECT `level1` INTO #x FROM `hierarchy_labels` LIMIT 1;
SET #s = CONCAT('SELECT `hlevel1` AS `', #x, '` FROM `hierarchy`');
PREPARE s FROM #s;
EXECUTE s;
DEALLOCATE PREPARE s;

Multiple values in MySQL variable

The following works as expected when there is a single value stored in a variable.
SET #a := "20100630";
SELECT * FROM wordbase WHERE verified = #a;
But it does not work when there are multiple values stored in a variable.
SET #a := "'20100630', '20100701' ";
SELECT * FROM wordbase WHERE verified in (#a);
Do I need to use prepared statements for this?
There's good solution described here: https://stackoverflow.com/a/11957706/1523961
So you can use something like this:
SET #a := '20100630,20100701';
SELECT * FROM wordbase WHERE FIND_IN_SET(verified, #a);
Also, if you're selecting the ids for #a from another table, you can come up with the following:
SET #a := (SELECT GROUP_CONCAT(id) FROM someTable where yourBooleanExpressionHere);
SELECT * FROM wordbase WHERE FIND_IN_SET(verified, #a);
You cannot (as far as I am aware) store multiple values in a MySQL user defined variable. What you have done is create a string which contains:
'20100630', '20100701'
That is not two separate values, but a single string value, just as this is a single string value:
SET #a := "It's a single string, and that's the problem";
You need to use two separate variables, or prepare a statement, like this:
SET #a := "20100630";
SET #b := "20100701";
SET #sql = CONCAT(
'SELECT * FROM wordbase WHERE verified IN (',
#a,
',',
#b,
')'
);
SELECT #sql;
+--------------------------------------------------------------+
| #sql |
+--------------------------------------------------------------+
| SELECT * FROM wordbase WHERE verified IN (20100630,20100701) |
+--------------------------------------------------------------+
PREPARE stmt FROM #sql;
EXECUTE stmt;
But that's kinda messy. Why do you need to use variables?
Using GROUP_CONCAT and GROUP BY one could pull all values ( i.e. an id ) into a variable like so:
SET #var := (SELECT GROUP_CONCAT(id) FROM `table` WHERE `verified` = #verified GROUP BY verified);
Something like this should work. Is it ok to use prepared statements to create temporary tables like this?
SET #a := "'20100630', '20100701'";
SET #sql = CONCAT('create temporary table pn1 SELECT * FROM wordbase WHERE verified IN (', #a, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
select * from pn1;
SELECT GROUP_CONCAT(field_table1 SEPARATOR ',') FROM table1 into #var;
then
SELECT * FROM table2 WHERE field_table2 in(#var);
works fine for me
FIND_IN_SET(column to find in , string csv) is a very handy method in case you have the string list of CSV:
SET #a := "'20100630', '20100701' ";
SELECT * FROM wordbase WHERE FIND_IN_SET(verified, #a);
if your variable is also coming from query then use this to set #a
SET #a := (SELECT GROUP_CONCAT(`id`) FROM `table`);
If you need to use your variable for a select or delete you can use select in the select:
delete from MPCurrentPayEntitlementAccrual where CurrentPayEntitlementID in ( select CurrentPayEntitlementID from MPCurrentPayEntitlement where PayRunID=myPayRunId by PayRunID desc);
That worked perfectly for me