MySQL SELECT MAX in equation - mysql

What I'm attempting to do find values in a table which are less than the MAX of another field, minus a numeric value. Eg:
...WHERE some_table.value_1 = 0 AND another_table.value_2 <= (SELECT MAX(another_table.value_3) - 5) ORDER BY...
However, this is not working! My joins are all fine, and the query runs without the 2nd part of the WHERE statement, but if you'd like to see the rest of the code for more info, let me know!
Cheers!
Sparkles*
ps all the values are integers

Here is a working example using joins, try to apply it to yours:
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t1.join_field = t2.join_field
WHERE t1.some_field = 1
AND t2.other_field <= (
SELECT (MAX(t22.third_field) - 5)
FROM table2 t22
);
If this is not exactly what you were looking for, please let me know and I will update it.

Use HAVING MAX(...)
Something like:
SELECT MIN(p.price) AS price, p.pricegroup
FROM articles_prices AS p
_YOUR_JOINED_TABLE_
WHERE p.articleID=10
GROUP BY p.pricegroup
HAVING MAX(p.price) > _VALUE_FROM_JOINED_TABLE_;

Related

Selecting data that does not have a reverse from table

having trouble figuring this out. The question is basically a table with 2 integer datas, p1 and p2. So lets say p1=100, p2=101. There may or may not exist another row with the values p1=101,p2=100 ( the reverse). I have to find a query that will list ONLY THE ROWS THAT DO NOT HAVE THEIR REVERSE VERSION. Hopefully i was able to explain the question clearly but englando is hard... Any help is much appreciated.
EDIT: Forgot to mention, i must not use INNER,OUTER JOIN statements in the solution of this question.
An example Table: Looking at this table, i need to select only the 3rd row p1=106, p2=104.
p1=101 , p2=103
p1=103 , p2=101
p1=106 , p2=104
p1=108 , p2=105
p1=105 , p2=108
Something like this should work:
SELECT t1.p1, t1.p2
FROM tbl as t1
LEFT JOIN tbl as t2
ON t1.p1 = t2.p2 AND t1.p2 = t2.p1
WHERE t2.p1 IS NULL
Check it here: http://sqlfiddle.com/#!9/28b0af/6
You can use least/greatest
select least(p1,p2) pl, greatest(p1,p2) pg
from tbl
group by least(p1,p2), greatest(p1,p2)
having count(*) = 1
This will work too (and no JOINs used):
select t1.p1,t1.p2
from tbl t1
where not exists(select p2,p1 from tbl where p2=t1.p1 and p1=t1.p2)
NOT EXISTS(...) is the most intuitive solution:
SELECT *
FROM thetable tt
WHERE NOT EXISTS (
SELECT * FROM thetable nx
WHERE nx.p1 = tt.p2
AND nx.p2 = tt.p1
);

Update two columns in MySQL from select statement

I'm trying to update two columns in MySQL:
update table1
set (table1.score, table1.count) =
(select (table2.maxScore - table2.score ) as diff, count(*)
from table2
where (table2.maxScore - table2.score) <= 600
and table2.age > 50
group by diff);
But, MySQL does not support this syntax. I've seen some examples using JOIN, but I can't make it work here. Many thanks for any help!
Maybe you should SET their values separately,
UPDATE scoresUniverse
SET scoreUniver.GNfemScore = (Analytics.GN_recency_max_score - Analytics.GN_recency_score ),
ScoresUniverse.GNfemCount = (Select count(*) from Analytics.GN_recency_score where (Analytics.PR_recency_max_score - Analytics.PR_recency_score) <= 600 and Analytics.Older_female_50 > 0)
I figured it out! MySQL can definitely update more than one column at once. I needed to change my original query because MySQL requires using JOIN with ON when updating more than one column. To prove it, I added an extra column "secondCol" to my example. I have looked all over the web for this, and never found the answer. I hope this helps some people.
update table1 join
(select (table2.maxScore - table2.score ) as diff, count(*) as count
from table2
where (table2.maxScore - table2.score) <= 600
and table2.age > 50
group by diff) as scores
on table1.count = scores.count
set table1.score = scores.diff, table1.secondCol = scores.count;

mySQL update a value

Modified some stuff from my pic so you guys can understand it
I have this database. I am trying to update a value from a table based on another value from an another table.
I want to update the SUM from salary like this :
( sum = presence * 5 )
This is what I've been trying to use ( unsuccessful )
update table salary
set suma.salary = users.presence * 5
FROM salary INNER JOIN users1 INNER JOIN presence on id_salary = id_presence
I am not sure what to do, I'd appreciate some help, Thanks
In MySQL to UPDATE tables with a join you use this syntax:
UPDATE table1, table2
SET table1.column = some expression
WHERE table1.column = table2.column
That said, even with the updated picture, in your SQL you are mentioning columns that I cannot understand in which table are to be found. You also have an inner join between salariu and users1, with no join condition. Could you please clean up the question and make everything clear?
Assuming you are making the updates to the db structure you were talking about, then you can start working on this one maybe:
UPDATE salary, presence
SET salary.sum = SUM(presence.hours) * 5
WHERE presence.id = salary.id
AND <some filter on the month that depends on salary.date>
Another way, but I'm not sure it is supported in all RDBMS, would be something like this:
UPDATE salary
SET sum = (
SELECT SUM(presence.hours) * 5
FROM user, presence
WHERE presence.id = salary.id
AND <some filter on the month that depends on salary.date>
)

CREATE VIEW WHERE SELECTid = VIEWrowID

Warning: vagueness & unclear questioning will abound because I know squat about databases.
I just discovered that I need to use views as surrogates for a cronned update statement. I can somewhat get the view to work, but I'm having trouble with rows.
This post helped me to bang out the update I need, but now that I know that views can run that update whenever it's needed rather than on a cron schedule, how can I set the view's column value based upon the view's row id or equivalent?
I've got the select I need:
SELECT SUM( table2.column1/ (
SELECT table2constant
FROM table3
)
FROM table2
WHERE table2table1id = table1id
table1id is the AI id column for table1. table2table1id is PKd to table1id. I'd like the view to have a column PKd to table1id like with table2, and the view needs to have every distinct table1id represented.
I'm sure the jargon's way off, but hopefully you can see what I need.
Will provide as many edits as necessary for clarity.
Many thanks in advance!
EDIT1
Should I create a trigger that creates the view upon insert to table1? Just found about materialization which is what I need/want?
Clarity
I need a summed value for each table1.table1id
Progress
With this code, I'm getting the first id from table1 and only the total sum. I need a sum for each table1.id.
CREATE VIEW db1.sums as
SELECT SUM( table2.column1/ (
SELECT table2constant
FROM table3
) as theSum, table1id
FROM table1, table2
WHERE table2.table2table1id = table1.table1id
To be clear I'm still not sure what you're trying to accomplish here but if what you posted works, try
SELECT table1.table1id,
SUM( table2.collumn1 ) / (SELECT table2constant FROM table3 ) as theSum
FROM table1, table2
WHERE table2.table2table1id = table1.table1id GROUP BY table1.table1id
you can replace (SELECT table2constant FROM table3 ) with your constant if it has no reason to otherwise be in the database (if it's not updated)
Its actually very simple. Here is an example of how you can do it.
SELECT SUM( table1.column / table2.column ), table1.*, table2.*
FROM table1, table2
WHERE table1.id = table2.column_id

SQL ANY & ALL Operators

I have started using sql and have heard much about the ANY and ALL operators. Can somebody explain to me the kind of queries they are used in and how they work?
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values. For instance:
select * from Table1 t1 where t1.Col1 < ANY(select value from Table2)
ANY means that the condition will be satisfied if the operation is true for any of the values in the range. ALL means that the condition will be satisfied only if the operation is true for all values in the range.
To use an example that might hit closer to home, doing this:
select * from Table1 t1 where t1.Col1 = ANY(select value from Table2)
Is the same as doing this:
select * from Table1 t1 where t1.Col1 in (select value from Table2)
I have heard much about the ANY and
ALL operators
I'm mildly surprised: I rarely see them used myself. Far more commonly seen are WHERE val IN (subquery) and WHERE EXISTS (subquery).
To borrow #Adam Robinson's example:
SELECT *
FROM Table1 AS t1
WHERE t1.Col1 < ANY (
SELECT value
FROM Table2
);
I more usually see this written like this:
SELECT *
FROM Table1 AS t1
WHERE EXISTS (
SELECT *
FROM Table2 AS t2
WHERE t1.Col1 < t2.value
);
I find this construct easier to read because the parameters of the predicate (t1.Col1 and t2.value respectively) are closer together.
Answers above addressed some aspects of "ANY" and did not address "ALL".
Both of these are more useful when comparing against another table and its entries are changing dynamically.
Especially true for < ANY and > ANY, since for static arguments, you could just take MAX/MIN respectively, and drop the "ANY".
For example, this query -
SELECT ProductName, ProductID FROM Products
WHERE ProductID > ANY (100, 200, 300);
can be simplified to -
SELECT ProductName, ProductID FROM Products
WHERE ProductID > 100;
Note that the "ALL" query will end up comparing one column value with ALL (...) which will always be false unless "ALL" arguments are identical.
For ex -
SELECT ProductName, ProductID FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails);
which is always empty/ false when subquery is multi-valued like -
SELECT ProductName, ProductID FROM Products
WHERE ProductID = ALL (10, 20, 30);
Adding to Adam's reply, be wary that the syntax can be ambiguous:
SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
Here ANY can be considered either as introducing a subquery, or as being an aggregate function, if the subquery returns one row with a Boolean value. (via postgresql.org)
Sample query that may put some context into this. Let's say we have a database of major league baseball players and we have a database of common Puerto Rican last names. Let's say somebody wanted to see how common Puerto Rican players are on the MLB. They could run the following query:
SELECT mlb_roster.last_name FROM mlb_roster WHERE mlb_roster.last_name = ANY (SELECT common_pr_names.last_name FROM common_pr_names)
What the query is doing here is comparing the last names on the MLB roster and displaying only the ones that are also found on the list of common Puerto Rican names.