Hey i'm trying to do some sql request but got a problem.
Firstly i do a replace request who filled my database.
After i do an update request that update some values.
And i'm doing another replace which is used to avoid duplicates, however some fields that were updated just before going to null because of the delete that is done before the insert (replace case)
How can I proceed so that the replace avoids putting some attribute to null and keep the values from the update?
Here is the sequence of the 3 queries that I make
REPLACE INTO all.serviceworker_subscriptions
(userId, userAgent, getDisplayMedia)
VALUES ('"+userId+"','"+userAgent+"','"+getDisplayMedia+"')
UPDATE all.serviceworker_subscriptions
SET dateDerniereConnexion = '"+socketDisconnectDate+"'
WHERE userId = '"+userId+"'
REPLACE INTO all.serviceworker_subscriptions
(userId, userAgent, getDisplayMedia)
VALUES ('"+userId+"','"+userAgent+"','"+getDisplayMedia+"')
My field : dateDerniereConnexion disappear after each 2nd replace ...
Thanks
Related
I am trying to use an update query to update fields from one table to another for fields but only if the fields in the table that i am updating into is blank. If they contain information, I do not want to overwrite the existing data
e.g
Field: Name
Table: Table 1
Update to: [Table2.][Name]
Criteria:
I am unsure of what to put in the criteria. I tried, 'Is Null', Like "".
Here is an example:
UPDATE MyTable SET MyTable.FieldB = "MyNewValue" WHERE (((MyTable.FieldB) Is Null));
Looking at the Query from within Access, you can switch to SQL view. You just need to put Is Null in the criteria column: UPDATE MyTable SET MyTable.FieldB = "MyNewValue" WHERE (((MyTable.FieldB) Is Null));
Furthermore, you can just write Is Null on alternate lines and it will count as OR.
I'm using a third party mysql table (ie I can't change any of its properties) and I have a row that has id (key), name and value.
I want to store unique cache keys into a row with the name cacheKeys.. and this is my sql statement
$query = "INSERT INTO ".$tableName." (name, value) VALUES ('CacheKeys', '".$key."') ON
DUPLICATE KEY UPDATE value = CONCAT_WS (',', $tableName.value, '$key')";
I've already implemented my caching algorithm, so that every time someone adds a cache key, I check to see if it already exists (from the CacheKeys row above), if it does I fetch it from cache.. otherwise I store it.
Problem is it seems that the sql write operation takes time, and it often stores duplicate cacheKeys
ie: currencies,defaultCurrencyId,user19,currency1,currency1,currency1,currency1,currency1
So I need to check to see that I'm not adding a duplicate key into the cacheKeys field.. and I need to do that using SQL (using php, ie regex etc would just be waaaay to expensive).
Try this::
INSERT INTO tb (firstname, lastname) VALUES ('Jack', 'Doe') IF NOT
EXISTS ( SELECT * FROM tb WHERE firstname='Jack' AND lastname='Doe' );
In my table I have two fields: v_id and ip_address. I want to insert some data into this table only if the IP address doesn't already exist.
After Google'ing I came across the INSERT IGNORE INTO statement, and this is my code:
public function update_visits($ip_address)
{
$sql = 'INSERT IGNORE INTO `24h_visits` (ip_address) VALUES (?)';
if($this->db->query($sql, array($ip_address)))
{
return TRUE;
}
return FALSE;
}
It runs fine and without errors, but duplicate rows are still being made, even if the same IP is passed in as a parameter.
Anyone got a clue? Thanks.
You have to create a UNIQUE index on ip_address for INSERT IGNORE to work:
ALTER TABLE 24h_visits
ADD UNIQUE INDEX(ip_address)
However, I haven't seen the entirety of your schema, but I would assume that there's a column that stores a timestamp of the last visit. It's the only way this would make sense (so you can purge visits older than 24 hours every now and then).
In this case, you actually don't want INSERT IGNORE, but INSERT ... ON DUPLICATE KEY UPDATE instead. Assuming you have a column called last_visit:
INSERT INTO 24h_visits (ip_address, last_visit)
VALUES ('$ip_address', NOW())
ON DUPLICATE KEY UPDATE last_visit = NOW();
With INSERT IGNORE, the new row is never inserted, and thus you would always have the first value ever inserted on last_visit, which (the way I see it) is not entirely correct.
Add the UNIQUE constraint to your ip_address column.
Then your query would fail if it attempts to add a duplicate ip_address row (unless you use INSERT IGNORE).
The other answers don't actually answer the question: Creating a unique index prevents the duplicate from being inserted, which is a good idea, but it doesn't answer "how to insert if not already there".
This is how you do it:
INSERT IGNORE INTO 24h_visits (ip_address)
select ?
where not exists (select * from 24h_visits where ip_address = ?)
Additionally, this approach does not require any changes to schema.
I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.
I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.
Thanks in advance.
I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.
Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:
UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();
EDIT: This actually works fine, no idea why I thought otherwise.
I have a prices table which includes a column price_was which needs to contain the highest ever value for prices.
Is it possible to do a REPLACE query which would update this if required?
The following (which is simplified and built dynamically in PHP) doesn't seem to work.
REPLACE prices
SET price = 1.99,
price_was = IF(1.99 > price_was, 1.99, price_was)
id_product = 1
I'm thinking perhaps it's not possible, but would love to hear otherwise since I'm updating many records and need to be as efficient as possible.
The query you posted is indeed valid, try it for yourself. I would use an UPDATE though since you're only updating one field and the REPLACE can possible over-write other column data you want left alone.
Try INSERT ... ON DUPLICATE KEY UPDATE instead:
INSERT INTO prices (price, price_was, id_product)
VALUES (1.99, 1.99, 1)
ON DUPLICATE KEY UPDATE
price_was = IF(VALUES(price) > price_was, VALUES(price), price_was)
id_product = VALUES(id_product)
This will do either an INSERT or an UPDATE, while the REPLACE statement does either an INSERT or a DELETE followed by an INSERT. You are not able to reference old values in a REPLACE statement, probably because of the DELETE/INSERT semantics. From the docs:
Values for all columns are taken from
the values specified in the REPLACE
statement. Any missing columns are set
to their default values, just as
happens for INSERT. You cannot refer
to values from the current row and use
them in the new row. If you use an
assignment such as SET col_name =
col_name + 1, the reference to the
column name on the right hand side is
treated as DEFAULT(col_name), so the
assignment is equivalent to SET
col_name = DEFAULT(col_name) + 1.