Adding Data Values inside a data table - mysql

Hey guys how do you add two values on separate fields but on the same table
for example:
tblbooks
Quantity
Borrowed
each time a user issue a book to a borrower the Quantity its reduce by 1 and Borrowed is added by 1....

INSERT INTO tablename(field1,field2)
VALUES(v1,v2)
In your case I guess you need to update.
Update yourtable
SET Quantity =Quantity-1,
Borrowed=Borrowed+1
Where userid=1

The way I generally do it is select the row I want to update using LinQ and then just update the values.
For example:
With (From rw In tblBooks Select rw Where rw.Item("MyCondition").ToString = "Condition").First
.Item("Quantity") = .Item("Quantity") - 1
.Item("Borrowed") = .Item("Borrowed") + 1
End With
... I didn't test this code, and it doesn't take into account conversion, error checking, etc, but I hope it conveys the idea...

Related

Sql: Find sum of column from second table using date from first table

I've been struggling to build a query that calculate the sum of column called 'TIDAL_VOLUME' with respect to date value that's coming from another table.
Please see the content of the Table_1:
Please see the content of the Table_2:
Note: TIDAL_VOLUME might have NULL as well.
Now, the start time for O2_Device value 'Endotracheal tube' is '2013-08-06 08:10:05' for same HADM_ID and SUBJECT_ID. and end time is whenever new O2_Device value comes in. In this case which is 'Nasal cannula'. Which means start time for 'Endotracheal tube' is '2013-08-06 08:10:05' and end time is '2013-08-06 10:15:05' for HADM_ID = 1 and SUBJECT_ID = 100.
Using that start time and end time criteria, I have to look for TIDAL_VALUE in Table_2. In this example it's 700, 800. Ans for TIDAL_VOLUME is 1500.
Please see the resultant output look like this:
Thanks in advance.
If you can add End_Time to the first table, you can use BETWEEN when you join the tables.
SELECT t1.HADM_ID, t1.Subject_ID, t1.ChartTime, SUM(t2.tidal_volume) AS tidal_volume
FROM Table_1 AS t1
JOIN Table_2 AS t2
ON t1.HADM_ID = t2.HADM_ID
AND t1.Subject_ID = t2.Subject_ID
AND t2.ChartTime BETWEEN t1.ChartTime AND t1.End_Time
GROUP BY t1.HADM_ID, t1.Subject_ID, t1.ChartTime

MySQL - Update column value based on joined table column value

I've been reading through SO and other sites, and have followed a few examples; however, my SQL statments is still not performing as required.
I have two tables
parts
============================
pmkParts fnkManufacturer
----------------------------
0 Penn-Union
1 Schneider
2 Telemecanique
and
manufacturer
===============================
Manufacturer pmkManufacturer
-------------------------------
Penn-Union 45
Schneider 56
Telemecanique 12
I want to change the parts table into
parts
============================
pmkParts fnkManufacturer
----------------------------
0 45
1 56
2 12
Here is the SQL statement I tried.
Update parts
SET parts.fnkManufacturer = (
SELECT manufacturer.pmkManufacturer
FROM manufacturer
WHERE manufacturer.pmkManufacturer = parts.fnkManufacturer
)
That is changing the correct column, but it is filling it with 'NULLS' rather than the foreign key (manufacturer). I think there should be a join somewhere in there, but I'm not sure where.
Any tips?
----------
EDIT: Answer:
Here is the SQL statement that worked. Thanks MarcB for the help.
Update parts
SET parts.fnkManufacturer = (
SELECT manufacturer.pmkManufacturer
FROM manufacturer
WHERE manufacturer.Manufacturer= parts.fnkManufacturer
)
Try changing your query like below using a update join query. Again, you are joining on the wrong column, you actually should be joining to manufacturer.Manufacturer column rather.
Update parts p
JOIN manufacturer m ON m.Manufacturer = p.fnkManufacturer
SET p.fnkManufacturer = m.pmkManufacturer;
Your pmkManufacturer looks like int so it is better to add new int field to parts, update it and then remove old column. Something like this.
alter table dbo.parts add pmkManufacturer int
update dbo.parts
set pmkManufacturer = m.pmkManufacturer
from dbo.parts p
inner join dbo.Manufacturer m on p.fnkManufacturer = m.manufacturer
The best solution, you could use INNER JOIN, I for example :
update parts p
inner join manufacturer m on
p.pmkManufacturer = m.Manufacturer
set p.pmkManufacturer = m.pmkManufacturer
Howerver, in your case, if I was wrong, you want to update pmkManufacturer while pmkManufacturer is actually the condition ON for INNER JOIN so I'm not sure that it'okay for request. If not, it isn't also difficult, you could add a new column : pmk_bis_manufacturer and set the value into this column, then delete the old column pmkManufacturer and change the name of new column if nescessary.
One tip for you : the name of columns database, I prefer setting :
pmk_manufacturer instead of pmkManufacturer because capital letter in the name
could make one problem in the futur. For example : for ORM Doctrine,
it isn't good :D

Select column to update based on value

What I am trying to do is reduce the time needed to aggregate data by producing a roll-up table of sorts. When I insert a record, an after insert trigger is fired which will update the correct row. I would update all of the columns of the roll-up table if I need to, but since there are 25 columns in the table and each insert will only update 2 of them, I would rather be able to dynamically select the columns to update. My current update statement in the after insert trigger looks similar to this:
update peek_at_chu.organization_data_state_log odsl
inner join ( select
lookUpID as org_data_lookup,
i.interval_id,
peek_at_chu.Get_Time_Durration_In_Interval1('s', new.start_time, new.end_time, i.start_time, i.end_time) as time_in_int,
new.phone_state_id
from
(peek_at_chu.interval_info i
join peek_at_chu.interval_step int_s on i.interval_step_id = int_s.interval_step_id)) as usl on odsl.org_date_lookup_id = usl.org_data_lookup
and odsl.interval_id = usl.interval_id
set
total_seconds = total_seconds + usl.time_in_int,
case new.phone_state_id
when 2 then
available_seconds = available_seconds + time_in_int
end;
In this, lookUpID is a variable previously declared in the trigger. The field that will dictate which field of the roll-up table to update is new.phone_state_id. The phone_state_id's are not consistent, that is some numbers are skipped in this table, so an update based on column number is out the window unless I create a mapping.
The case option throws an error but I am hoping to use something similar to that instead of 25 if statements if I can.
You have to update all the columns, but use a conditional to determine whether to give it a new value or keep the old value:
set total_seconds = total_seconds + usl.time_in_int,
available_seconds = IF(new.phone_state_id = 2, available_seconds + time_in_int, available_seconds)
Repeat the pattern in the last line for all the other columns that need to be updated conditionally.

MySQL inner join, check from different table

I have 2 tables formatted as below:
INSERT INTO `mixture` (`id`, `item`) VALUES
(1,'water'),
(2,'gas'),
(3,'oil'),
(4,'ice');
another table
INSERT INTO `check` (`name`, `seen`) VALUES
('Nadia','[2][3]'),
('Omer','[1][4][2]');
result needed:
How do I get the result to show this?
Nadia will only see information that has mixture.id 1 & 4, while
Omer will only see information that has mixture.id 3
Each time they see the result, mixture.id will be added to their check.seen status, so that they will not see the same information in the future.
This is what I have done so far:
SELECT
mixture.*,
check.seen,
check.name
FROM mixture
INNER JOIN check
WHERE check.seen not like '%[mixture.id]%'
Thanks in advance
Please make my day.
The index should be a numeric type like a integer not a string, no quotes around the numbers
Your another table will have a row for each mixture known by the person
('Nadia',2)
('Nadia',3)
('Omer',1)
('Omer',4)
('Omer',2)
A select for Nadia will return a record set with 2 records, one for each mixture she knows, 3 for Omer
Select seen FROM anothertable where name = 'Nadia'
a join will return the correct mixture item string from your first table.
http://www.w3schools.com/sql/sql_join.asp

mysql - satisfy composite primary key while using 'insert into xxx select'

I am importing data to a table structured: content_id|user_id|count - all integers all comprise the composite primary key
The table I want to select it from is structured: content_id|user_id
For reasons quite specific to my use case, I will need to fire quite a lot of data into this regularly enough to want a pure MySQL solution
insert into new_db.table
select content_id,user_id,xxx from old_db.table
I want each row to go in with xxx set to 0, unless this would create a duplicate key, in which case I wish to increment the number, for the current user_id/content_id combination
Not being a MySQL expert, I tried a few options like trying to populate xxx by selecting from the target table during insert, with no luck. Also tried using ON DUPLICATE KEY to increment counters instead of the usual UPDATE. But it all seemed a bit daft so I thought I would come here!
Any ideas anyone? I have a backup option of wrapping this in PHP, but it would drastically raise the overall running time of the script in which this would be the only non-pure MySQL part
Any help really appreciated. thanks in advance!
--edit
this may sound really awful in principle. but id settle for a way to do it in an update after entering random numbers (i have sent in random numbers to allow me to continue other work at the moment) - and this is a purely dev setup
--edit again
12|234
51|45
51|45
51|45
23|67
would ideally insert
12|234|0
51|45|0
51|45|1
51|45|2
23|67|0
INSERT INTO new_db.table (content_id, user_id, cnt)
SELECT old.content_id, old.user_id, COUNT(old.*) - 1 FROM old_db.table old
GROUP BY old.content_id, old.user_id
this would be the way I would go, so if 1 entry it would put 0 on cnt, for more it would just put 1-2-3 etc.
Edit:
Your correct answer would be somewhat complicated but I tested it and it works:
INSERT INTO newtable(user_id,content_id,cnt)
SELECT o1.user_id, o1.content_id,
CASE
WHEN COALESCE(#rownum, 0) = 0
THEN #rownum:=c-1
ELSE #rownum:=#rownum-1
END as cnt
FROM
(SELECT user_id, content_id, COUNT(*) as c FROM oldtable
GROUP BY user_id, content_id ) as grpd
LEFT JOIN
(SELECT oldtable.* FROM oldtable) o1 ON
(o1.user_id = grpd.user_id AND o1.content_id = grpd.content_id)
;
Assuming that in the old db table (source), you will not have the same (content_id, user_id) combination, then you can import using this query
insert newdbtable
select o.content_id, o.user_id, ifnull(max(n.`count`),-1)+1
from olddbtable o
left join newdbtable n on n.content_id=o.content_id and n.user_id=o.user_id
group by o.content_id, o.user_id;