Maybe I'm totally wrong and it's not pssible to do in MySQL. But, what I wanted to do is to fill out column row base in a select query:
For example:
Table 1:
IdNode NodeName NodeContact NodeStatus Nodegroup
1 Machine1 IT 1 IT
2 Machine2 IT 0 IT
3 Machine3 IT 1 IT
4 Machine4 IT 1 Others
4 Machine5 IT 1 Others
Table 2
IdGroup GroupName NodesManagedbyGroup
1 IT ??
2 others ??
Having those two tables, I would like to fill out (automatically) all rows in column NodesManagedbyGroup in the table2.
Manually it would be:
SELECT COUNT(*) FROM table1 where MemberOfGroup='IT';
result value Int = 3
Then
update table2 NodesManagedbyGroup = 3 where GroupName='IT';
There is any way that MySQL do it for me automatically
You can use triggers to do this - you'd create triggers for insert, update and delete on table 1 to update table 2.
This is generally a bad idea though - it's duplicating information around the database, denormalizing the schema.
Alternatively, you can create a view which calculates this data on the fly and behaves like a table when querying.
Use multiple UPDATE syntax with selecting counts in subquery as a sample:
UPDATE
table2
INNER JOIN
(SELECT COUNT(1) AS gcount, Nodegroup FROM table1 GROUP BY Nodegroup) AS counts
ON table2.GroupName=counts.Nodegroup
SET
table2.NodesManagedbyGroup=table1.gcount
You could set a job that performs a stored procedure every 15 minutes or so?
Related
I'm trying to fill a certain column of a SQL table with data from another table. I have a column named "size" in my table which should return the number of rows in the 2nd table where the id of both rows is the same. Is there a way to populate a SQL column based on a certain command? I would love to be able to fill the column based on this command:
SELECT count(*)
FROM second_table
WHERE id = "row_id";
Here is a sample database with the two tables:
Table 1
Name
id
tiger
1
lion
2
gazelle
1
Here is the desired output for Table 2:
id
Number of Animals
1
2
2
1
I am trying to fill the Number of Animals column but do it automatically and dynamically when another row is added or deleted to Table 1, which is why I want the Select count(*) SQL statement as the code for the column.
One method is a correlated subquery:
update table1 t1
set size = (select count(*)
from table2 t2
where t2.id = t1.id
);
If you need to do this dynamically (as data is inserted), then you would need to use a trigger. However, I would suggest that you calculate the value as needed, unless there is a specific reason why you need to store it.
I guess you need something like this:
CREATE TRIGGER UpdateAnimalCountTable2
AFTER INSERT ON `Table1` FOR EACH ROW
begin
DECLARE NewCount int;
SELECT count(1)
INTO #NewCount
FROM Table1
WHERE Table1.id= NEW.id;
UPDATE Table2
SET NoOfAnimals = #NewCount
WHERE id = NEW.id;
END;
Above is the trigger which will be executed after every insert in Table1 and will update the count in Table 2 for ID which just got inserted in Table1.
select 2 + 2 is a valid mysql statement, but in oracle I have to provide a table name select 2 + 2 from foo (or dual table). Is there any way to not set the from statement? I wonder why it is not optional in Oracle. Providing a fake table sounds dummy when it could be optional as other RDBMs.
You have to select from something; in Oracle, it is the DUAL table:
SQL> select 3 + 6 from dual;
3+6
----------
9
It is a SYS owned table and contains a single row:
SQL> select * From dual;
DUMMY
--------------------
X
Therefore, it is useful for such things (where you need to fetch a single line).
The way you put it (select ... from foo) is kind of OK, if foo also contains one row. But, what if it doesn't? Have a look: there are 4 departments in the dept table:
SQL> select 3 + 6 from dept;
3+6
----------
9
9
9
9
So - use DUAL :)
Using PL/SQL Subprograms in Oracle you can execute 2 + 2, for example
DECLARE
v_sum number;
BEGIN
v_sum:= 2 + 2;
END;
This is not related to SQL in general, but from SQL* Plus or in other ides running as script(F5), you can do arithmetic without specifying a table
VARIABLE b NUMBER
EXEC :b := 2+2;
PRINT b;
PL/SQL procedure successfully completed.
B
----------
4
use dual because it is a single row single column table with a datatype of VARCHAR2(1) in it.ALways use dual when you want to fetch single output.it has a dummy value of X.
AS wiki says :- The idea was that you could do a JOIN to the DUAL table and create two rows in the result for every one row in your table. Then, by using GROUP BY, the resulting join could be summarized to show the amount of storage for the DATA extent and for the INDEX extent(s). The name, DUAL, seemed apt for the process of creating a pair of rows from just one.[1]
The original DUAL table had two rows in it (hence its name), but subsequently it only had one row.
Below is the table i am trying to write a query for to add new rows for every user.
My question is how do i add a new row for every user? Which means for userId 2 I add AccId 4 and similarly for 7 and 8. Since there is no concept of for loop in sql, do i make use of while? If so, how to loop through the userIds since the IDs are not in equal increments?
something like this maybe:
Insert Into mytable (UserID, AccID)
Select UserID, max(accId)+1
From MyTable
Group By UserID
You can re-run it every time, you will create the next value.
Untested on a MySql server:
INSERT INTO MyTable ( ID, AccId )
SELECT MyValues.ID, MyValues.Espr1
FROM (SELECT MyTable.ID, Max([AccId]+1) AS Espr1
FROM MyTable
GROUP BY MyTable.ID) AS MyValues;
Basically we prefetch Id a AccId grouping the values of Id and grabbing the Max of AccId.
Then we add these rows to the main table. Repeating the query we will add the value 5 (AccId) and so on, always adding 1
In a previous question I asked how I could sum up a total based on some conditions: Count total on couple of conditions
Suppose I have a table like this:
id col1 col2 col3
1 a 1 k1
2 a 2 k2
3 a -3 k3
4 b 3 k4
Now, when I get id=1, I want to delete all the rows where col1=a.
When I get id=4, I want to delete all the rows where col1=b.
How would I do this in SQL?
I tried based upon previous answer:
DELETE FROM table WHERE (col1) IN (SELECT col1 FROM table WHERE id = '1')
But that gave me an error: #1093 - You can't specify target table 'table' for update in FROM clause
This has been many times on stackowerflow, you cannot UPDATE/DELETE table with data from nested select on the same table. There're two ways to do this:
Load all data before (for example via php, sql procedure)
Create temporary table like the one you're using, clone data and use temporary table to select items
i have another suggested solution for this. What if you create a STORED PROCEDURE for this problem?
like this:
DELIMITER $$
CREATE PROCEDURE `DeleteRec`(IN xxx varchar(5))
BEGIN
DECLARE oID varchar(5);
SET oID := (SELECT col1 FROM table WHERE id = '1');
DELETE FROM table WHERE col1 = oID;
END$$
DELIMITER ;
do this helps you?
Query to Where X update Y and where A update B in a Mysql Table column.
How can I Do this in MYsql in one query on the same column in a specific table.
I want to search and replace multiple values in a table column.
Conditions in table1 in column1
Where X update Y
and
Where a update b
and
Where 1 update 2
and
Where 3 update 4
and
Where value1 update value 2
And so on.
I can individually do this but how can I do this faster? Is there a mysql function to help me with this?
I have about 120 columns with 200 search and replace/update values for each column.
Thanks.
You can use something like this:
update table table set A = if(conditionA, newA, A), B = if(conditionB, newB, B)
But I expect it will be slower than 2 separate updates, because it is trying to reset every row's value back to itself when it doesn't match the condition.
You could optimise it somewhat by adding:
update table table set A = if(conditionA, newA, A), B = if(conditionB, newB, B)
where conditionA or conditionB
This might be quicker than 2 queries in some circumstances.
You could do something like this:
UPDATE table1
SET
col1 = CASE WHEN col2 THEN a ELSE col1 END,
col3 = CASE WHEN col4 THEN b ELSE col3 END
Note that this sets a value back to itself if the condition fails, effectively causing it to be unchanged.