run select and update query together - mysql

Hi
I want to use an update inside of select statement e.g:
Select * from admin where id=1 join update data set col1='Mydata'
the table names and format is not important I want to know it's possible or not? If yes, How?

An update inside af a select statement is not possible.
But...
you can use the Update-Statement with specific conditions so the result is the one you need.
Here's a rough example based on your statements:
update data, admin
set data.col1 = 'Mydata'
where data.pkey = admin.pkey
and admin.id = 1;
There should be a link between the two tables which I assumed as "pkey". To be more precise one needs to have a look at the table definitions.

No it is not possible. you must run them separately

You may be able to use JOIN and a WHERE clause in your UPDATE statement. But, you would need to have some way of joining the two tables.
UPDATE admin,data SET data.col1='MyData' WHERE admin.id=1 AND admin.id = data.admin_id;
Or something along those lines. Not sure what your tables look like. Read about the UPDATE statement in the reference manual for your database.

Related

How to make Query Builder By Update Join 2 Tables In The Phalcon

I want to make QueryBuilder on the Update Join 2 Tables. But I don't know sintaks it. Please Write codes to me about how to make it. I give example query of the following below:
UPDATE Teachers
INNER JOIN Education
ON Education.id=Teachers.id
SET
Teachers.userid=:userid:,
Teachers.fullname=:fullname:,
Teachers.birthday=:birthday:,
Teachers.gender=:gender:,
Teachers.currentjob=:currentjob:,
Education.primaryschool=:primaryschool:,
Education.juniorhighschool=:juniorhighschool:,
Education.seniorhighschool=:seniorhighschool:,
WHERE Teachers.id=:id:
As far as i know PHQL doesn't allow update like this. When you write PHQL update query in phalcon it'as actually making SELECT query, and calling update method to make sure all the events, validation etc are fired for the models. With joins this is obviously a problem how to exactly do it, beacause you might join some model which doesn't have relations provided.
Phalcon just don't support JOINS with UPDATE, you need to use raw query.

How to replace "*" into all columns when writing SQL

It is a bad habbit to use select "*" when writing SQL with JDBC.
But what if there are many columns in the table(s), how can I easily pickup some wanted columns in the SQL rather than using *?
For example,suppose I have table1 and table2,which have 10 columns each. I need most of their columns, but I do not want to use SELECT * FROM table1 inner join table2 on table1.id=table2.id since this is a bad practice. Actually I only need SELECT column1,column4,column5(most of them)...... from table1 inner join table2 on table1.id=table2.id.
So, do I have a way that replace * into all columns and then I can just COPY this text and remove some columns which I don't need and remain what I want rather than type each column name?
If you're using SQL Server, an easy trick is to open a database in Management Studio, right-click on a table and select "Select top 1000 Rows" from the context menu. You'll get all the fields listed one by one. You can copy and paste the text wherever you want.
I don't know which IDE you're using let alone which DBMS, but there's probably a trick like this one in it.
Try using the query below which is use to get all the columns of a specific table. Hope it helps you.
SELECT name FROM sys.all_columns WHERE object_id = OBJECT_ID('MyTableHere')
In MySQL, try the code below or you can refer in this Documentation:
SHOW COLUMNS FROM MyTableNameHere;

SQL newbie: execution order of subqueries?

Warning: This is a soft question, where you'll be answering to someone who has just started teaching himself SQL from the ground up. I haven't gotten my database software set up yet, so I can't provide tables to run queries against. Some patience required.
Warnings aside, I'm experimenting with basic SQL but I'm having a little bit of a rough time getting a clear answer about the inner workings of subqueries and their execution order within my query.
Let us say my query looks something like shit:
SELECT * FROM someTable
WHERE someFirstValue = someSecondValue
AND EXISTS (
SELECT * FROM someOtherTable
WHERE someTable.someFirstValue = someOtherTable.someThirdValue
)
;
The reason I'm here, is because I don't think I understand fully what is going on in this query.
Now I don't want to seem lazy, so I'm not going to ask you guys to "tell me what's going on here", so instead, I'll provide my own theory first:
The first row in someTable is checked so see if someFirstValue is the same as someSecondValue in that row.
If it isn't, it goes onto the second row and checks it too. It continues like this until a row passes this little inspection.
If a row does pass, it opens up a new query. If the table produced by this query contains even a single row, it returns TRUE, but if it's empty it returns FALSE.
My theory ends here, and my confusion begins.
Will this inner query now compare only the rows that passed the first WHERE? Or will it check all the items someTable and someOtherTable?
Rephrased; will only the rows that passed the first WHERE be compared in the someTable.someFirstValue = someOtherTable.someThirdValue subquery?
Or will the subquery compare all the elements from someTable to all the elements in someOtherTable regardless of which passed the first WHERE and which didn't?
UPDATE: Assume I'm using MySQL 5.5.32. If that matters.
The answer is that SQL is a descriptive language that describes the result set being produced from a query. It does not specify how the query is going to be run.
In your case the query has several options on how it might run, depending on the database engine, what the tables look like, and indexes. The query itself:
SELECT t.*
FROM someTable t
WHERE t.someFirstValue = t.someSecondValue AND
EXISTS (SELECT *
FROM someOtherTable t2
WHERE t.someFirstValue = t2.someThirdValue
);
Says: "Get me all columns from SomeTable where someFirstValue = someSecondValue and there is a corresponding row in someOtherTable where that's table column someThirdValue is the same as someFirstValue".
One possible way to approach this query would be to scan someTable and first check for the first condition. When the two columns match, then look up someFirstValue in an index on someOtherTable(someThirdValue) and keep the row if the values match. As I say, this is one approach, and there are others.

SQL update query for balances using Access raises 'Operation must use an updateable query'

I have the following query (MS Access 2010) which I'm trying to use to update a table with a running balance:
UPDATE Accounts a SET a.CurrentBalance =
(SELECT sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount)) +
(select a1.openingbalance
from accounts a1 where a1.accountid = a.accountid) AS TotalAmount
FROM transactions t inner join (
transactiontypes tt inner join
categories c on c.categoryid = tt.categoryid)
on t.transactiontypeid = tt.transactiontypeid);
The tables used are:
A work around for the "Query must use an updateable query" is to use a temporary table and then update the final target data based on the aggregated data in the temporary table. In your case, as mwolfe suggests, you have an aggregate function in the inner select query. The workaround could provide a quick fix for this situation, as it has for me.
Ref: http://support.microsoft.com/kb/328828
This article helped me understand the specifics of the situation and provided the work around:
http://www.fmsinc.com/MicrosoftAccess/query/non-updateable/index.html
You cannot use aggregate functions (like SUM) in an update query. See Why is my query read-only? for a full list of conditions that will cause your query to be "non-updateable".
The Access db engine includes support for domain functions (DMax, DSum, DLookup, etc.). And domain functions can often allow you to circumvent non-updateable query problems.
Consider DSum() with these 3 rows of data in MyTable.
id MyNumber
1 2
2 3
3 5
Then in the Immediate window, here are 2 sample DSum() expressions.
? DSum("MyNumber", "MyTable")
10
? DSum("IIf(id=1,MyNumber * -1, MyNumber)", "MyTable")
6
I think you may be able to use something like that second expression as a replacement for the sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount) part of your query.
And perhaps you can use a DLookup() expression to get your TotalAmount value. Unfortunately I got frustrated trying to translate your current SQL to domain functions. And I realize this isn't a complete solution, but hope it will point you to something useful. If you edit your question to show us brief samples of the starting data and what you hope to achieve from your UPDATE statement based on that sample data, I would be willing to have another look at this.
Finally, consider whether you absolutely must store CurrentBalance in a table. As a rule of thumb, avoid storing derived values. Instead, use a SELECT query to compute the derived value when you need it. That approach would guarantee CurrentBalance is always up-to-date whenever you retrieve it. It would also spare you the effort to create a working UPDATE statement.

Mysql "magic" catch all column for select statement

Is there a way that I can do a select as such
select * from attributes where product_id = 500
would return
id name description
1 wheel round and black
2 horn makes loud noise
3 window solid object you can see through
and the query
select * from attributes where product_id = 234
would return the same results as would any query to this table.
Now obviously I could just remove the where clause and go about my day. But this involves editing code that I don't really want to modify so i'm trying to fix this at the database level.
So is there a "magical" way to ignore what is in the where clause and return whatever I want using a view or something ?
Even if it was possible, I doubt it would work. Both of those WHERE clauses expect one thing to be returned, therefore the code would probably just use the first row returned, not all of them.
It would also give the database a behaviour that would make future developers pull their hair out trying to understand.
Do it properly and fix the code.
or you could pass "product_id" instead of an integer, if there's no code checking for that...so the query would become:
select * from attributes where product_id = product_id;
this would give you every row in the table.
If you can't edit the query, maybe you can append to it? You could stick
OR 1=1
on the end.
You may be able to use result set metadata to get what you want, but a result set won't have descriptions of fields. The specific API to get result set metadata from a prepared query varies by programming language, and you haven't said what language you're using.
You can query the INFORMATION_SCHEMA for the products table.
SELECT ordinal_position, column_name, column_comment
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'products' AND schema_name = 'mydatabase';
You can restructure the database into an Entity-Attribute-Value design, but that's a much more ambitious change than fixing your code.
Or you can abandon SQL databases altogether, and use a semantic data store like RDF, which allows you to query metadata of an entity in the same way you query data.
As far out as this idea seems I'm always interested in crazy ways to do things.
I think the best solution I could come up with is to use a view that uses the products table to get all the products then the attributes table to get the attributes, so every possible product is accounted for and all will get the same result