How to find applicable grid in MySQL? - mysql

I have a complex situation, as I am not able to write a single query for this.
I have a table like below:
ID MIN MAX PLEVEL
1 0 .50 P1
2 .51 1.00 P2
3 1.01 1.02 P3
I have a variable which can have any value like .23, .75 etc
I need query to check the PLEVEL related to this like
if variable = .23 than PLEVEL = P1
if varable = .75 than PLEVEL = P2

You can do this to look up the appropriate row in your table for a particular variable. (http://sqlfiddle.com/#!9/822676/9/0)
SET #variable := 0.23;
SELECT #variable, PLEVEL
FROM tbl
WHERE #variable <= `MAX` AND #variable > `MIN`
But, your table data may contain a flaw. What happens if your variable value is 0.505? It won't match any row.

You haven't given a lot of detail to go on, but it sounds like you want this:
SELECT PLEVEL from table WHERE variable >= MIN and variable <= MAX;
assuming min and max are number columns and you only want plevel returned.

The Immediate If (IIF) statement can be helpful
SELECT ID ,IIF(variable=.23,'P1',IIF(variable=.75,'P2','')) as Plevel From MyTable
Or you might want to look at the CASE command

Related

how to get average value from 2 colomn ini mysql

i have table = table_a
and filed =
val1,val2,val3 =(10,10,7)
i want get Avg value from val1,val2,val3 on mysql, i was try with AVG(val1,val2,val3) from table_a it's not work,
somebody can help me?
thanks
Since you want to get the average of the columns not rows, just perform basic calculation
(val1 + val2 + val3) / 3.0 AS Average

Comparing counts across two tables

Given two tables...
tblEvents (fldEventID, fldAECap, fldDWCap, fldWSCap)
tblSignUps (fldSignUpID, fldEventID, fldPosition)
where a value of 1 in fldPosition relates to fldAECap, a value of 2 relates to fldDWCap, a value of 3 relates to fldWSCap; I need to prevent any new records from being inserted into tblSignUps if the count of fldPosition values is equal to each related CAP value. For instance, we may only have 3 allotted positions for fldAECAP and that position value occurs 3 times in fldPosition for that given EventID
The basic logic would come down to...
INSERT INTO tblSignUps
VALUES(NULL,12,3)
WHERE fldWSCap > COUNT(fldPosition(3))
How would I do this?
A way to write the required basic logic is this:
INSERT INTO tblSignUps
select NULL,12,3 from dual
where exists (
select * from tblEvents where
fldEventId = 12 and
fldWSCap > (select count(*) from tblSignUps where fldEventId = 12 and fldPosition = 3)
);
Obviously this works only for the field fldWSCap. The others two require a similar statement where the fld*Cap change according to the fldPosition value.

How to return all matches in mysql where value occurs in string at position n?

Im looking to run a query in phpmyadmin (mysql) that wil check a table for a specific value at a specific postion in a string, i'm new to mysql and this is what i've tried but there's a syntax issue. I'm looking to find the value "1" at position 5 and display all those users that possess this.
SELECT*
FROM`user`
WHERE`options`LOCATE(`options`,1,5)
LIMIT 0 , 30
regards,
Silo
Locate is for finding a value ANYWHERE in a string. You want a specific location only, so use substr() instead:
SELECT *
FROM user
WHERE substr(options, 5, 1) = '1'
You could try
SELECT*
FROM`user`
WHERE options LIKE '____1%'
LIMIT 0 , 30
Another ;)
SELECT *
FROM user
WHERE instr(options, '1') = 5
Duh .. Well won't work since it only returns the first occurnace :$ But CHECK the reference,
SQLFIDDLE using Locate()
Sample data:
COL1 COL2
G11 112
G11-1 0
G11-2 2
G12-2 111
Query1:
-- to check on varchar columns
SELECT *
FROM tablex
where locate('1',col1,5)
;
Results on varchar:
COL1 COL2
G11-1 0
Query 2:
-- to check on int columns
SELECT *
FROM tablex
where locate(1,col2,2)
;
Results on int:
COL1 COL2
G11 112
G12-2 111

Break Numbers List Into Min and Max Ranges

Brain is not working today and my google skills are failing me.
I have a column of numbers ranging from 1 - 1000. I want to dump the min and max values for 100 (or whatever I chose) record ranges into a temp table. The plan is to use this temp table to process ranges of records (in this example 100 at a time) in a larger table.
Swear I have done this before with a CTE but then I had something to group on. Here I just want to break up a single list of numbers into ranges of X.
The output from the temp table should look like:
Min Max
0 99
100 199
200 299
300 399
etc.
Thanks!
You can use this trick from Stuart Ainsworth:
http://codegumbo.com/index.php/2009/01/25/building-ranges-using-a-dynamically-generated-numbers-table/
Numbers tables are awesome, but he uses a dynamically generated numbers table, which is even awesome...r.
If you know all numbers are present in the source table, you can use a recursive CTE to generate the number ranges:
; with numbers as
(
select 0 as a
, 99 as b
union all
select a+100
, b+100
from numbers
where a < 900
)
select *
from numbers
If the source table is sparsely populated, you can limit it to numbers that are actually present like:
... insert CTE from above here ...
select min(ot.NumberColumn)
, max(ot.NumberColumn)
from numbers
left join
OtherTable ot
on ot.NumberColumn between numbers.a and numbers.b
group by
numbers.a
enter code hereI have been having a play with a CTE after you posted this and came up with the following, I would be interested to hear if it works for you at all.
DECLARE #segment int = 100
;
WITH _CTE
(rowNum, value)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY col01) -1, col01
FROM dbo.testTable
)
SELECT rowNum/#segment AS Bucket, MIN(Value) AS MinVal, MAX(Value) AS MaxVal
FROM _CTE
group by rowNum/#segment
ORDER BY Bucket
;
col01 in this case is the column that you want the min/max range values from, as is TestTable.

Need Help streamlining a SQL query to avoid redundant math operations in the WHERE and SELECT

*Hey everyone, I am working on a query and am unsure how to make it process as quickly as possible and with as little redundancy as possible. I am really hoping someone there can help me come up with a good way of doing this.
Thanks in advance for the help!*
Okay, so here is what I have as best I can explain it. I have simplified the tables and math to just get across what I am trying to understand.
Basically I have a smallish table that never changes and will always only have 50k records like this:
Values_Table
ID Value1 Value2
1 2 7
2 2 7.2
3 3 7.5
4 33 10
….50000 44 17.2
And a couple tables that constantly change and are rather large, eg a potential of up to 5 million records:
Flags_Table
Index Flag1 Type
1 0 0
2 0 1
3 1 0
4 1 1
….5,000,000 1 1
Users_Table
Index Name ASSOCIATED_ID
1 John 1
2 John 1
3 Paul 3
4 Paul 3
….5,000,000 Richard 2
I need to tie all 3 tables together. The most results that are likely to ever be returned from the small table is somewhere in the neighborhood of 100 results. The large tables are joined on the index and these are then joined to the Values_Table ON Values_Table.ID = Users_Table.ASSOCIATED_ID …. That part is easy enough.
Where it gets tricky for me is that I need to return, as quickly as possible, a list limited to 10 results where value1 and value2 are mathematically operated on to return a new_ value where that new_value is less than 10 and the result is sorted by that new_value and any other where statements I need can be applied to the flags. I do need to be able to move along the limit. EG LIMIT 0,10 / 11,10 / 21,10 etc...
In a subsequent (or the same if possible) query I need to get the top 10 count of all types that matched that criteria before the limit was applied.
So for example I want to join all of these and return anything where Value1 + Value2 < 10 AND I also need the count.
So what I want is:
Index Name Flag1 New_Value
1 John 0 9
2 John 0 9
5000000 Richard 1 9.2
The second response would be:
ID (not index) Count
1 2
2 1
I tried this a few ways and ultimately came up with the following somewhat ugly query:
SELECT INDEX, NAME, Flag1, (Value1 * some_variable + Value2) as New_Value
FROM Values_Table
JOIN Users_Table ON ASSOCIATED_ID = ID
JOIN Flags_Table ON Flags_Table.Index = Users_Table.Index
WHERE (Value1 * some_variable + Value1) < 10
ORDER BY New_Value
LIMIT 0,10
And then for the count:
SELECT ID, COUNT(TYPE) as Count, (Value1 * some_variable + Value2) as New_Value
FROM Values_Table
JOIN Users_Table ON ASSOCIATED_ID = ID
JOIN Flags_Table ON Flags_Table.Index = Users_Table.Index
WHERE (Value1 * some_variable + Value1) < 10
GROUP BY TYPE
ORDER BY New_Value
LIMIT 0,10
Being able to filter on the different flags and such in my WHERE clause is important; that may sound stupid to comment on but I mention that because from what I could see a quicker method would have been to use the HAVING statement but I don't believe that will work in certain instance depending on what I want to use my WHERE clause to filter against.
And when filtering using the flags table :
SELECT INDEX, NAME, Flag1, (Value1 * some_variable + Value2) as New_Value
FROM Values_Table
JOIN Users_Table ON ASSOCIATED_ID = ID
JOIN Flags_Table ON Flags_Table.Index = Users_Table.Index
WHERE (Value1 * some_variable + Value1) < 10 AND Flag1 = 0
ORDER BY New_Value
LIMIT 0,10
...filtered count:
SELECT ID, COUNT(TYPE) as Count, (Value1 * some_variable + Value2) as New_Value
FROM Values_Table
JOIN Users_Table ON ASSOCIATED_ID = ID
JOIN Flags_Table ON Flags_Table.Index = Users_Table.Index
WHERE (Value1 * some_variable + Value1) < 10 AND Flag1 = 0
GROUP BY TYPE
ORDER BY New_Value
LIMIT 0,10
That works fine but has to run the math multiple times for each row, and I get the nagging feeling that it is also running the math multiple times on the same row in the Values_table table. My thought was that I should just get only the valid responses from the Values_table first and then join those to the other tables to cut down on the processing; with how SQL optimizes things though I wasn't sure if it might not already be doing that. I know I could use a HAVING clause to only run the math once if I did it that way but I am uncertain how I would then best join things.
My questions are:
Can I avoid running that math twice and still make the query work
(or I suppose if there is a good way
to make the first one work as well
that would be great)
What is the fastest way to do this
as this is something that will
be running very often.
It seems like this should be painfully simple but I am just missing something stupid.
I contemplated pulling into a temp table then joining that table to itself but that seems like I would trade math for iterations against the table and still end up slow.
Thank you all for your help in this and please let me know if I need to clarify anything here!
** To clarify on a question, I can't use a 3rd column with the values pre-calculated because in reality the math is much more complex then addition, I just simplified it for illustration's sake.
Do you have a benchmark query to compare against? Usually it doesn't work to try to outsmart the optimizer. If you have acceptable performance from a starting query, then you can see where extra work is being expended (indicated by disk reads, cache consumption, etc.) and focus on that.
Avoid the temptation to break it into pieces and solve those. That's an antipattern. That includes temp tables especially.
Redundant math is usually ok - what hurts is disk activity. I've never seen a query that needed CPU work reduction on pure calculations.
Gather your results and put them in a temp table
SELECT * into TempTable FROM (SELECT INDEX, NAME, Type, ID, Flag1, (Value1 + Value2) as New_Value
FROM Values_Table
JOIN Users_Table ON ASSOCIATED_ID = ID
JOIN Flags_Table ON Flags_Table.Index = Users_Table.Index
WHERE New_Value < 10)
ORDER BY New_Value
LIMIT 0,10
Return Result for First Query
SELECT INDEX, NAME, Flag1, New_Value
FROM TempTable
Return Results for count of Types
Select ID, Count(Type)
FROM TempTable
GROUP BY TYPE
Is there any chance that you can add a third column to the values_table with the pre-calculated value? Even if the result of your calculation is dependent on other variables, you could run the calculation for the whole table but only when those variables change.