mysql create view with mysql query that contains variable - mysql

I have the below syntax that I want to use to create a MySQL view:
create view `ViewName` as (select
v_starting.callingname,
v_starting.geofence,
v_starting.`updatetime`,
#lastGroup := #lastGroup + if( #lastAddress = v_starting.geofence
AND #lastVehicle = v_starting.callingname, 0, 1 ) as GroupSeq,
#lastVehicle := v_starting.callingname as justVarVehicleChange,
#lastAddress := v_starting.geofence as justVarAddressChange
from
v_starting,
( select #lastVehicle := '',
#lastAddress := '',
#lastGroup := 0 ) SQLVars
order by
v_starting.`updatetime` )
This fails with error:
#1351 - View's SELECT contains a variable or parameter
How can I get around this? Thanks a million.

As documented under CREATE VIEW Syntax:
A view definition is subject to the following restrictions:
[ deletia ]
The SELECT statement cannot refer to system or user variables.

Think you would need to do this using a subselect to count the records.
Something like this:-
SELECT v_starting.callingname,
v_starting.geofence,
v_starting.`updatetime`,
Sub1.PrevRecCount ASGroupSeq
FROM v_starting
INNER JOIN (SELECT a.updatetime, COUNT(DISTINCT b.callingname, b.geofence ) AS PrevRecCount
FROM v_starting a
LEFT OUTER JOIN v_starting b
ON a.updatetime > b.updatetime
AND a.callingname != b.callingname
AND a.geofence != b.geofence
GROUP BY a.updatetime) Sub1
Not 100% sure about this as I am dubious about how you are ordering things to get your count presently.

for variable using, try to use a stored procedure or a custom function

Related

mysql works fine after first time

I have a strange problem which is when I run the sql command first time it shows wrong result, but when I run the same code for second time the result is correct.
The wrong result is:
The expected result is:
the sql command is:
SELECT srNumber, end_on, start_on, teamEntityId
FROM (
SELECT srNumber, end_on, start_on, teamEntityId,
#lastrow := IF(#sr_Number = srNumber, #lastrow + 1,
IF(#sr_Number := srNumber, 1, 0)) AS lastrow
FROM assign
CROSS JOIN (SELECT #lastrow := 0, #sr_Number = '') AS vars
ORDER By srNumber, assignId DESC) AS t
WHERE t.lastrow = 1 AND t.teamEntityId = '00000168752ac161-02420aff00230001'
In more recent versions of MySQL, you need to order the data before using variables. So replace:
FROM assign
with:
FROM (SELECT a.* FROM assign a ORDER BY srNumber, assignId DESC) a
I would like to thank Alex and Salman A who solved the problem which is:
replace the below code
#sr_Number = ''
to
#sr_Number := ''

MySql : How to get the four unique results only?

I am trying to get the these four highlighted results only. I tried grouping them but still not getting the required results.
The query is :-
Set #filter := 0.00;
SELECT autorates2.ID, autorates2.Car, autorates2.Origin , autorates2.Destination, autorates2.Carrier,
#FuelLevy := ( autorates2.Buy * Carrier.FuelLevy) + autorates2.Buy AS 'AfterFuelLevy',
#GST :=(#FuelLevy * 0.10) + #FuelLevy AS 'AfterGST',
#filter := (Select Margin.MarginPer from Margin where #GST between Margin.Low and Margin.High ),
#Margin := (#filter * #GST) + #GST AS 'Sell',
autorates2.OriginType, autorates2.DestinationType, CONCAT(autorates2.OriginType, autorates2.DestinationType) as'ser'
from Margin, Carrier
RIGHT JOIN autorates2 on autorates2.Carrier = Carrier.Carrier
Where autorates2.Origin = 'Melbourne' AND autorates2.Destination = 'Sydney' AND autorates2.Car = '4WD/Van' AND Carrier.Disabled = 0 AND autorates2.GoodsAllowed = 0
Group by ser
ORDER by MIN(Sell),ser
And the output I get is where the highlighted one are wrong results:-
This is the actual results that needed.
Table 1:
Table 2:
Table 3:
use corelated-sub query like below way, as you not shared your all source column name so i guess price is a column
select * from yourtable t1 where price in
(
select min(price) from yourtable t2 where t1.car=t2.car
and t1.depot=t2.depot and t1.door=t2.door
and t1.destinationtype=t2.destinationtype and t1.ser=t2.ser
)

How to SET user defined variables in dynamic SQL query?

Where does the SET assignment (SET #running_total_available := 0;) go when using dynamic SQL as in my query below?
My query works fine as shown, but the "#running totals..." crash the query when I use SET #running_total_available := 0
and reset each row to "0" without the use of SET.
I'm stumped. Thanks!
$sql = "
SELECT
SQL_CALC_FOUND_ROWS
#running_total_available := 0,
product_source,
username,
product_short_name,
noci_count,
item_listing_id,
IF(num_purchased=0,'', num_purchased) AS num_purchased ,
IF(num_available=0,'', num_available) AS num_available,
IF(num_sold=0,'', num_sold) AS num_sold,
i.tot_items,
date(date_listing_noci) AS date_listing_noci,
IFNULL(date(date_listing_removed),'') AS date_listing_removed,
#running_total_purchased:=#running_total_purchased + i.num_purchased AS running_total_purchased,
#running_total_available:=#running_total_available + i.num_available AS running_total_available,
#running_total_sold:=#running_total_sold + i.num_sold AS running_total_sold,
#running_total_item:=#running_total_item + i.num_sold + i.num_available AS running_total_item,
#running_total_noci:=#running_total_noci + i.noci_count AS running_total_noci
FROM
(SELECT
product_source,
item_listing_id,
p.product_short_name,
username,
noci_count,
IF(num_purchased=0,0,num_purchased) AS num_purchased,
IFNULL(num_available,0) AS num_available,
IFNULL(num_sold,0) AS num_sold,
IFNULL(num_sold,0) + IFNULL(num_available,0) AS tot_items,
date(date_listing_noci) AS date_listing_noci,
IFNULL(date(date_listing_removed),'') AS date_listing_removed
FROM `investigation`
JOIN product p USING (product_id)
WHERE 1 ";
*** dynamic constructs here ***
# close query
$sql.= " ) i ";
$result = $objDbMysqli->query($sql);
Initialize it in a cross-joined subquery:
SELECT
...
FROM (
...
JOIN product p USING (product_id)
WHERE 1
) i
CROSS JOIN (select #running_total_available := 0) initvars
Use it on your own risk because the execution order is not guaranteed.

mysql variable with #variables for calculated values

I have a mysql query where I need to calculate values like ROUND(SUM(temp.total_pq),2) multiple times, so I defined variables to avoid repeating them.
But the line 5 in the query returns wrong value in the results. The value for #diff_client_partner_qtty := ROUND((#partner_qtty_all_runs - #client_qtty_all_runs), 2) AS diff_client_partner_qtty is always NULL the first time I run and thereafter always 84.
I asked the in-house DBA and he says I should not use variables in my query like this because the order in which mysql will set values for the variable is not predictable and hence I may get NULL value.
But why? Also can someone please propose then another way whereby I can avoid rewriting ROUND(SUM(temp.total_pq),2) multiple times other than a subquery. I would prefer to avoid a subquery because I think even in its current form query is not that readable.
SELECT temp.dtaccounted AS accounting_period,
#partner_qtty_all_runs := ROUND(SUM(temp.total_pq),2) AS partner_qtty_all_runs,
ROUND(temp.mmq,2) AS mopay_qtty,
#client_qtty_all_runs := ROUND(SUM(temp.total_cq),2) AS client_qtty_all_runs,
#diff_client_partner_qtty := ROUND((#partner_qtty_all_runs - #client_qtty_all_runs), 2) AS diff_client_partner_qtty,
#partner_gtv := ROUND(temp.total_pq_gtv, 2) AS partner_gtv,
#client_gtv := ROUND(temp.total_cq_gtv,2) AS client_gtv,
#diff_client_partner_gtv := ROUND((#partner_gtv - #client_gtv), 2) AS diff_client_partner_gtv,
temp.stariffcurrency AS tariffcurrency,
ROUND(#diff_client_partner_gtv * ffactor, 2) AS diff_client_partner_gtv_eur,
temp.scountry AS country,
temp.spartnererpid AS partner_erp_id,
c.name AS partner_name,
temp.nproducttype AS product,
temp.capping
FROM
(SELECT SUM(npartnerquantity) AS total_pq,
SUM(nmindmaticsquantity) AS mmq,
SUM(nclientquantity) AS total_cq,
SUM(dgrosstariff * npartnerquantity) AS total_pq_gtv,
SUM(dgrosstariff * nclientquantity) AS total_cq_gtv,
nrun,
vb.scountry,
vb.spartnererpid,
dtaccounted,
stariffcurrency,
vb.nproducttype,
cq.bisenabled AS capping
FROM report_table vb,
client_table cq
WHERE vb.accperiod > '2013-12-01'
AND vb.partnerid = cq.partnerid
AND vb.scountry = cq.scountry
AND vb.nproducttype = cq.nproducttype
AND (cq.dtvalidto IS NULL
OR cq.dtvalidto > vb.accperiod)
GROUP BY scountry,
nproducttype,
partnerid,
nrun,
accperiod
) temp,
customer c,
currency_conversion cc
WHERE temp.partnerid = c.erp_id
AND temp.total_pq <> temp.total_cq
AND cc.scurrencyfrom = temp.stariffcurrency
AND cc.scurrencyto = 'EUR'
AND cc.dtrefdate = temp.accperiod
GROUP BY temp.scountry,
temp.partnerid,
c.name,
temp.nproducttype,
temp.accperiod
ORDER BY temp.accperiod,
temp.scountry,
temp.partnerid,
temp.nproducttype,
temp.capping \G;

Coldfusion CFScript Query with MySQL Assignment Operator

I want to select currentrow as part of my query - I know I can loop over queries and get the currentrow variable, but I'm doing a QoQ before I use the rows and I want to keep the original rows, e.g.
//Original query
1, Audi
2, BMW
3, Skoda
//QoQ
1, Audi
3, Skoda
This is the code I've got:
q = new Query( datasource = application.db.comcar );
q.setSQL('
SELECT make, #rownum := #rownum +1 AS `rownumber`
FROM cars, ( SELECT #rownum :=0 )
LIMIT 10
');
r = q.execute().getResult();
But it's throwing the following error:
Parameter '=' not found in the list of parameters specified
SQL: SELECT make, #rownum := #rownum + 1 AS `rownumber` FROM cars, ( SELECT #rownum :=0 ) LIMIT 10
This will work in cfquery but I'd like to use it in CFScript. Is there an alternative to using := or some way of escaping this in the query.
It looks like this is a bug in Coldfusion. I could change my code to use cfquery but I'd rather not mix script and tags in my page.
So my workaround was is as follows:
/*
* based on the existing query 'tmpFields'
*/
// build array of row numbers
arrRowNumbers = [];
cntRowNumbers = tmpFields.recordCount;
for( r = 1; r <= cntRowNumbers; r++ ) {
arrayAppend( arrRowNumbers, r );
}
// add a new column with the new row number array
queryAddColumn( tmpFields, "fieldNumber", "integer", arrRowNumbers );