CREATE VIEW WHERE SELECTid = VIEWrowID - mysql

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

Related

MariaDB dependent subquery in the not in subquery

I have the following query that retrieves all rows (x:text,y:text) from table1 where text in column x is not yet in table2.x
Given:
We are using MariaDB;
the column x is defined as not nullable text in both tables;
No indices are there (the application is very dynamic that we do not want to use indices);
we need the column y to be retrieved as well (EXCEPT won't work).
The execution plan always shows the inner query as a Dependent Subquery and the performance is super bad.
SELECT DISTINCT(table1.x), table1.y
FROM table1
WHERE table1.x IS NOT NULL
AND table1.x NOT IN (
SELECT DISTINCT table2.x from table2
WHERE table2.x IS NOT NULL
)
Could you please suggest some better solution to this issue?
Thanks
See if the following is any better for you:
select table1.x, table1.y -- use Distinct only if x & y have duplicates
from table1 t1
where not exists (select * from table2 t2 where t2.x = t1.x);
You obviously don't need to check for NULL is columns do not allow NULL. Probably the optimizer would ignore this anyway.

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
);

why using IN (or NOT IN) clause in a query makes it really slow

I have a query:
SELECT DISTINCT field1 FROM table1 WHERE field2 = something
(table1 contains 1 million records, execution time:0.106sec, returns: 20 records)
Another query
SELECT DISTINCT similarField1 FROM table2 WHERE similarField2 = somethingElse
(table2 contains half million records, execution time:0.078sec, returns: 20 records)
Now if I run a query, by combining above both:
SELECT DISTINCT field1 FROM table1 WHERE field2 = something AND field1 NOT IN (SELECT DISTINCT similarField1 FROM table2 WHERE similarField2 = somethingElse)
It does't give result even running for 10mins. Why it has became dramatically slow, and what could be a potential solution.
edit: I am using MySQL with dbvisualizer 6.5
You don't need to use DISTINCT on the sub-query. Try to use NOT EXISTS which probably is more efficient in SQL-Server:
SELECT DISTINCT field1
FROM table1
WHERE field2 = #something
AND NOT EXISTS
(
SELECT 1 FROM table2
WHERE table2.similarfield1 = table1.field2
AND table2.similarfield2 = #somethingelse
)
Edit: Since you have updated the tags, i'm not sure if this is more efficient in MySql. However, i'd prefer NOT EXISTS anyway since it also works with NULL values(if you use IS NULL) and is easier to read and to maintain.
my query and advice are similar to #TimSchmelter.
In fact you should not use distinct at all. First you should remove distinct and check if you are getting duplicate records you have just ask part of your problem.Table design are not clear.
You should post your complete problem and query here without any hesitant. Also don't forget to apply index on feild2, feild1,similarField1,similarField2.
SELECT DISTINCT field1
FROM table1 tbl1
WHERE field2 = something
AND NOT EXISTS (
SELECT similarField1
FROM table2 tbl2
WHERE tbl1.field1 = tbl2.similarField1
AND similarField2 = somethingElse
)

Mysql error 1093 - Can't specify target table for update in FROM clause - update column in same table

I know there are a lot of topics on this but I can't figure out how should I rewrite my query to make it work :(
Here my query. It's just should take currency rate from other table and calculate cost
update site_s_client_base_price
SET calculated_price_in_base_currency =
SELECT (site_s_currencies.rate * site_s_client_base_price.supplier_price) from
site_s_currencies, site_s_client_base_price
WHERE site_s_currencies.currency_id=site_s_client_base_price.currency_id
Please, help me with this
You can't seletc and update in the same table because it's locked, use the example above or use
Update TABLE1 t1 set FIELD1= ( select field1 from TABLE1 t2 where .....)
In your case you can fix this by fixing the subquery. You don't need to mention the outer table in the inner from clause. You want a correlated subquery:
update site_s_client_base_price bp
SET calculated_price_in_base_currency =
(SELECT c.rate * bp.supplier_price
FROM site_s_currencies c
WHERE c.currency_id = bp.currency_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.