To append comma separated value no duplicates in mysql update Query - php

I am storing table data as comma separated values like this
id name fk_id
1 abc 2,4,6
2 def 2,7,8
Now, I want to use CASE WHEN or some function in Update Query of MySQL which updates the field if no duplicate value:
For example, same value for fk_id then ignores else update like if 10 for id 1 then update but if 7 for id 2 then ignore
id name fk_id
1 abc 2,4,6,10
2 def 2,7,8
I tried the following code:
if(
find_in_set($fk_id,fk_id),
fk_id,
CONCAT_WS(',', fk_id, $fk_id)
)
But not working.

Just update your code like as
set fk_id = if(find_in_set($fk_id,fk_id),
fk_id,
CONCAT(fk_id, ',', $fk_id)
)

Try this :
$sql = "
UPDATE `test`
SET `fk_id` = CONCAT(fk_id, ',','" . $fk_id . "')
WHERE `fk_id` REGEXP ',?(" . $fk_id . "),?'
";
NOTE : REGEXP is not the best option when it comes to speed.

Related

Update primary key, sorted by another column, duplicate handling?

Trying to basically re-count the primary column, meaning updating from the first to the last, incrementing the value with each row. First I am selecting,
select
`someid`,
`time`
from
`table`
ORDER BY
`time` ASC
fetching the result,
$data = new SplFixedArray($query->num_rows);
$data = $query->fetch_all();
and updating the table.
for($i=1; $i<count($data); $i++){
print_r("UPDATING | New someid: " . $i . " WHERE old someid: " . $data[$i][0] . " AND time = " . $data[$i][1] . "<br />");
$query = $mysqli->query("UPDATE `table` SET `someid` = '" . $i . "' WHERE `time` = '" . $data[$i][1] . "' AND `someid` = '".$data[$i][0]."'");
}
What confuses me is, that the first few entries aren't sorted correctly. It's like
someid | time
--------------
0 | 0
2 | 1
1 | 2
7 | 3
11 | 4
6 | 5
It's because of duplicates. After the 15ish rows in "someid" there is a gap and it jumps to 60. So after that there are no more duplicate someids. But how can I handle the first few rows? If I want to update someid to 2 but 2 is already existent?
Any way to handle that without using too many querys?
Edit:
Maybe it's unclear to some. Basically I am trying to refresh the int-values from a primary column. So basically I am counting them and enter their appropriate number into someid, sorted by sometime. Sometime is datetime. So the earliest "sometime" would get "someid" = 1.
At the moment, someid has gaps. 1..2..3..4..5..6..7..15..16..17..18..30..31..32
Updating, like I am doing now, doesn't work until I reach a gap. Because I am trying to write a duplicate value. Updating the first someid to 1, which might be of value 11, does not work because someid 1 is already existent somewhere.
I would update someid 15 to 8, because it's the next number. This works because 8 to 14 are missing, and I am not duplicating a value.
One solution might be to create another loop and first update every someid to some made up number, maybe start counting from row->count, incrementing for every row. After that, I can update them as I'd do normally. But isn't there a better solution?
// UPDATE:
This:
SET #count = 0;
UPDATE `table` SET `table`.`someid` = #count:= #count+ 1;
"Resets" the IDs, but it doesnt sort them by time.
Trying this:
SET #count = 0;
UPDATE `table` SET `table`.`someid` = #count:= #count+ 1;
ORDER BY `time` DESC;
Gives me the following error:
Duplicate entry '1' for key 'PRIMARY'

How do I run a SQL query only if it has no specific value in it

I have a problem with an sql query i want to run. Basically I want to update a table only if it has no '.' in it (for example 1 row has value '2' and the other row will have value '2.1', in this case i would only want to update the value with a 2.) This is what I tried
UPDATE new__tags SET sort_order = 1 WHERE id = '.$id. ' AND sort_order NOT LIKE "%.%"';
Unfortunately this did not work and still updated everything.
Thanks for your time.
If your sort_order is an INT , use CAST
"UPDATE `new__tags` SET `sort_order` = 1 WHERE `id` = '.$id. ' AND CAST(`sort_order` as CHAR) NOT LIKE '%.%'";
Try this:
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND CAST(sort_order AS CHAR) NOT LIKE '%.%'";
try this i tested with phpmyadmin
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND sort_order NOT REGEXP '[.]'";

how to replace database value by update table php

I have created two tables subscription_pending and subscription_complete
subscription_complete contain
id mag1 mag2 mag3 mag4
4 100 0 100 0
subscription_pending contain
id mag1 mag2 mag3 mag4
4 100
I have insert value by following command
$final_q= "INSERT INTO `subscription_complete` (`id`, `mag1`, `mag2`, `mag3`, `mag4`) VALUES ('".$row_q['id']."','".$row_q['mag1']."','".$row_q['mag2']."','".$row_q['mag3']."','".$row_q['mag4']."'
i want to update the subscription_complete table without replacing its value i.e. 100 for that i hvae write following query
$final_q1= "update subscription_complete set mag1='".$row_q['mag1']."',mag2='".$row_q['mag2']."',mag3='".$row_q['mag3']."',mag4='".$row_q['mag4']."' where id='".$row_q['id']."'";
can you tell me how to set 100 value in remaining column where the value is 0 ?
Thank you in advance !!
This assumes the empty fields in subscription_pending contain NULL, not empty strings.
UPDATE subscription_complete AS c
JOIN subscription_pending AS p ON p.id = c.id
SET c.mag1 = IFNULL(p.mag1, c.mag1),
c.mag2 = IFNULL(p.mag2, c.mag2),
c.mag3 = IFNULL(p.mag3, c.mag3),
c.mag4 = IFNULL(p.mag4, c.mag4)
If they're actually empty strings, use IF(p.magX = '', c.magX, p.magX) instead of the IFNULL test.

PHP Mysql How to make a field get the same value of the auto increment id [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL trigger to update a field to the value of id
Please I have a table with three fields :
Id (auto increment)
GroupById
Text
And I want when inserting a new row : If I left the field groupById blank, it must get by default the same value of the field Id.
Please have you any Idea ? Thanks in advance.
Edit : My code :
mysql_query("INSERT INTO group SET GroupById = (must get the current Id), Text = 'bla bla bla' ");
How about a trigger:
DELIMITER $$
CREATE TRIGGER trg_yourtable
BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
IF NEW.GroupById IS NULL THEN
SET NEW.GroupById = (
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'yourtable'
);
END IF;
END $$
I'm not sure how safe this is... or what happens when you insert multiple rows from one query, or when two connections attempt to insert at the same time... but it works.
This simple SQL should do what you want:
INSERT INTO myTable (GroupById, Text) VALUES (NULL, 'your text');
SET #lastID = LAST_INSERT_ID();
UPDATE myTable SET GroupById = #lastID WHERE Id = #lastID;
Use a stored procedure
Get the MAX id
Add 1 to it and add insert it into both rows
You get the desired result in a single transaction.
Hope this helps.
Use this function | Tested
Example of use:
function get_current_insert_id($table)
{
$q = "SELECT LAST_INSERT_ID() FROM $table";
return mysql_num_rows(mysql_query($q)) + 1;
}
$txt = "text";
$groupID = '';
if ( empty($groupID) ) { $groupID = get_current_insert_id(test); }
$query = mysql_query("INSERT INTO test VALUES ('', '$groupID', '$txt') ");
if ( $query ) { echo 'Saved using ID:' . $groupID; } else { echo 'Oh noes!' . $query; }
Looks like you might need to run 2 queries:
insert into 'table' ('GroupById', 'Text') VALUES ('{group id}', '{sometext}')
update 'table' set GroupById = id where GroupById = null - it mightbe 0 instead of null depending on what you insert in db.
You can always optimize it through indexes, limits, order.

Add Prefix to auto-increment in mysql db

I have my database with table test1.
It has a primary id "Id" which is auto-increment.
Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as
PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).
No. Either add the prefix in the query, or use a view instead.
Not really, but you can use another column (but a view)
this is already covered here:
MySQL Auto Increment Custom Values
Yes you can do it if you have INT prefix. You have id as INT in table
// START PREFIX
$query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1");
// GET THE LAST ID MAKE SURE IN TABLE YOU 9991
while ($row = mysql_fetch_object($query)) {
$lastId = $row->id;
}
list($prefix,$Id) = explode('999',$lastId );
$Id = ($Id+1);
$new_id = '999'.$Id;
// END PREFIX
$insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
Hi, I made it work in this way :
Products Table (products):
id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
Products Sequence Table (productidseq):
id(AI, PK, NOT NULL)
Before Insert Trigger in Products Table:
CREATE DEFINER=`root`#`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
BEGIN
insert into productidseq (id) values(NULL);
set new.id_prod = concat('PROD or any prefix here',last_insert_id());
set #productId = new.id_prod; -- To use outside of trigger this variable is useful.
END
When you run below query :
insert into products (name) values('Bat');
data inside tables will we be like this :
products:
id | name
---|-----
1 | Bat
productidseq:
id
---
1
If any better way than this or any cons with this, please comment below. Thanks.

Categories