UPDATE using JOIN appends only first row value to another table, why? - php

I have a target table which crossed over 1M rows. Each time I will be getting 50K rows which may contain multiple duplicated entries. Hence I have decided to store CSV data into a temp table, then from temp_table to target_table by comparing rows between two tables...
If duplicated entries found append data from temp_table to target_table else Insert into the table... I am using partition here, so ON DUPLICATE key update is not working here.. in temp_table I am not using any KEYS
I have two tables which look like below
temp_table
Name | Type
John | Civil
John | Mech
target_table
Name | Type
John | Civil
When I run below query, I am getting an output of single row
UPDATE target_table JOIN temp_table
ON temp_table.Name = target_table.Name
SET target_table.Type = IF((LOCATE(temp_table.Type, target_table.Type) > 0)
target_table.Type,CONCAT(target_table.Type,',',temp_table.Type))
target_table
Name | Type
John | Civil
I am expecting output to be like below
target_table
Name | Type
John | Civil, Mech
May I know where it went wrong?

you should use a group_concat and use a subquery in join
UPDATE target_table
JOIN (
select name, group_concat(Type) grouped
from temp_table
group by name
) t ON t.Name = target_table.Name
SET target_table.Type = t.grouped

I suspect (but don't know for sure) and hopefully someone who does know will jump in and correct me, that an update join does not create a cartesian product in the way that a select would. As an attempted proof
truncate table temp_table;
insert into temp_table values
( 'John' , 'mech' ),
( 'John' , 'abc' );
truncate table target_table;
insert into target_table values
('john', 'civil', 9 );
UPDATE target_table JOIN temp_table
ON temp_table.Name = target_table.Name
set target_table.type = (concat(target_table.Type,',',temp_table.Type));
select * from target_table;
+------+------------+------+
| Name | Type | LOC |
+------+------------+------+
| john | civil,mech | 9 |
+------+------------+------+
1 row in set (0.00 sec)
note that abc from temp_table is ignored and mech is selected purely by chance.
if we change the order in temp_table
truncate table temp_table;
insert into temp_table values
( 'John' , 'abc' ),
( 'John' , 'mech' );
truncate table target_table;
insert into target_table values
('john', 'civil', 9 );
UPDATE target_table JOIN temp_table
ON temp_table.Name = target_table.Name
set target_table.type = (concat(target_table.Type,',',temp_table.Type));
select * from target_table;
we get
+------+-----------+------+
| Name | Type | LOC |
+------+-----------+------+
| john | civil,abc | 9 |
+------+-----------+------+
1 row in set (0.02 sec)
where abc is picked purely by chance.
In my view the safest way to do this is on a row by row basis ie a cursor.

Related

Rewrite of counter by partition

I use mysql and php with phpmyadmin. I have major problem with a partition based counter that I wan't to improve but my knowledge on sql prevents me from doing that. Im struggling very much with this.
I want the duplicated data in my table to have a counter that adds a number after a value if this value gets a duplicated value and then restarts from 1 until a new value is met and so on. Here is what the final result should look like
---------------------------
1 | Josh-1
---------------------------
2 | Josh-2
--------------------------
3 | Josh-3
--------------------------
4 | Josh-4
--------------------------
5 | Fred-1
--------------------------
6 | Fred-2
--------------------------
7 | Fred-3
-------------------------
I had gotten help with this counter here before but it's not working as I wan't it to. Also when I have pressed the insert button in my form the table looks like this in phpmyadmin after I reload it
---------------------------
1 | Josh-1-1-1
---------------------------
2 | Josh-2
--------------------------
3 | Josh-3
--------------------------
4 | Josh-4
--------------------------
5 | Fred-1
--------------------------
6 | Fred-2
--------------------------
7 | Fred
-------------------------
Whats going on here? The code that I seek help with rewriting is this
UPDATE usermeta u1,
(SELECT
u1.`id`, CONCAT(u1.`name`,'-',ROW_NUMBER() OVER(PARTITION BY u1.`name` ORDER BY u1.`id`)) newname
FROM
usermeta u1 JOIN (SELECT `name` , COUNT(*) FROM usermeta GROUP BY `name` HAVING COUNT(*) > 1) u2
ON u1.`name` = u2.`name` ) u3
SET u1.`name` = u3.`newname`
WHERE u1.`id` = u3.`id`
Could this code be rewritten so it creates a table of numbered names and duplicates that looks like the first table example and work like it should in phpmyadmin ? All help is very much appreciated. Keep in mind that I am a struggling moderate sql user.
Possible solution - BEFORE INSERT trigger and additional MyISAM table with secondary autoincrement:
Working table
CREATE TABLE user (id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(127));
Additional table
CREATE TABLE user_index (id INT AUTO_INCREMENT,
name VARCHAR(127),
PRIMARY KEY (name, id)) ENGINE=MyISAM;
Trigger
CREATE TRIGGER insert_user_index
BEFORE INSERT ON user
FOR EACH ROW
BEGIN
DECLARE new_index INT;
INSERT INTO user_index (name) VALUES (NEW.name);
SET new_index = LAST_INSERT_ID();
DELETE FROM user_index WHERE name = NEW.name AND id < new_index;
SET NEW.name = CONCAT_WS('-', NEW.name, new_index);
END
Insert rows - the AI index is added to the name. Check the result.
INSERT INTO user (name) VALUES
('Josh'),
('Josh'),
('Fred'),
('Josh'),
('Fred'),
('Fred'),
('Josh');
SELECT * FROM user;
id | name
-: | :-----
1 | Josh-1
2 | Josh-2
3 | Fred-1
4 | Josh-3
5 | Fred-2
6 | Fred-3
7 | Josh-4
Look what is stored in additional table now.
SELECT * FROM user_index;
id | name
-: | :---
3 | Fred
4 | Josh
db<>fiddle here
If your working table user exists already, and it contains some data, then you'd create additional table and fill it with data using, for example,
CREATE TABLE user_index (id INT AUTO_INCREMENT,
name VARCHAR(127),
PRIMARY KEY (name, id)) ENGINE=MyISAM
SELECT MAX(SUBSTRING_INDEX(name, '-', -1) + 0) id,
SUBSTRING_INDEX(name, '-', 1) name
FROM user
GROUP BY 2;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=38f028cfe1c9e85188ab0454463dcd78

PHP Mysql Insert Batch if not exist

I have searched that there is already a way in inserting avoiding the duplicate error
ref: MySQL: Insert record if not exists in table
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Unknown'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+---------+-----------+------+
| id | name | address | tele |
+----+---------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
| 3 | Unknown | Unknown | 022 |
+----+---------+-----------+------+
is there a way for this to do in batch?
or how is the format in adding data as a batch
ref: insert multiple rows via a php array into mysql
Planning to integrate this one
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
is there a way?
I would suggest using the ON DUPLICATE KEY syntax for this. This will simplify the query, and allow the use of the VALUES() statement, which is handy to pass parameters from your application.
For this to work, you need a unique (or primary key) constraint on colum name. Create it if it does not exist:
create unique index idx_table_listnames on table_listnames(name);
Then, you can do:
insert into table_listnames(name, address, tele)
values('Unknown', 'Unknown', '022')
on duplicate key update name = values(name)
The conflict clause traps violations on the unique index, and performs a no-op update.
Side note: use parameterized queries to pass data from your application to the query; escaping input is not enough to make your query safe.

query set value with data from related table

so, i have done a big mistake when i designing my table for salesreport that looks like this
+----+------------+--------------+-------+
| id | company_id | company_code | value |
+----+------------+--------------+-------+
| 1 | 0 | 67 | 100 |
| 2 | 0 | 55 | 200 |
+----+------------+--------------+-------+
i just recently notice it and add new column called company_id which is in the company table that looks like this
+----+--------------+------+
| id | company_code | name |
+----+--------------+------+
| 1 | 55 | XX |
| 2 | 67 | XA |
+----+--------------+------+
in the past i create relationship with company_code since i thought it will always unique but not auto increment, the code is created manually from company list in existing record.
i then realise that it will be better to create a relationship between table by using id so instead of using company_code it should be company_id on my salesreport table that pointing to id column in company table
and now there is more than a thousand record that already in mysql database that referencing relationship using company_code and i want to know is there one times mysql query that i can run to fix it?
and i come up with this kind of query
UPDATE salesreport SET company_id = '1' WHERE company_code = '67';
but i think since both tables company and salesreport already had a relationship why can't it just like this
UPDATE salesreport SET company_id = company.id WHERE company_code = company.company_code;
but i don't think it will be work, it needs more query to know that i selecting company table and then match salesreport.company_code with company.company_code and if it is match then set salesreport.company_id with company.id
well i think that is how it goes... but i have no idea what is the query to do just that.. so maybe someone can help me and provide a lazy-elegant solution to this.
thank you by the way.
Here is a solution to your request:
UPDATE salesreport
LEFT JOIN company ON company.company_code = salesreport.company_code
SET salesreport.company_id = company.id;
I have created a SQLFiddle for you to test the results: http://rextester.com/HNJ85353
HerŅƒ is a full test case:
CREATE TABLE IF NOT EXISTS p1929_salesreport (id INTEGER PRIMARY KEY AUTO_INCREMENT,
company_id INTEGER,
company_code INTEGER,
value INTEGER);
INSERT INTO p1929_salesreport (company_id, company_code, value) VALUES (0, 67, 100);
INSERT INTO p1929_salesreport (company_id, company_code, value) VALUES (0, 55, 200);
CREATE TABLE IF NOT EXISTS p1929_company (id INTEGER PRIMARY KEY AUTO_INCREMENT,
company_code INTEGER,
name TEXT);
INSERT INTO p1929_company (company_code, name) VALUES (55, "XX");
INSERT INTO p1929_company (company_code, name) VALUES (67, "XA");
/* before changes */
SELECT * FROM p1929_company;
SELECT * FROM p1929_salesreport;
/* actual query */
UPDATE p1929_salesreport
LEFT JOIN p1929_company ON p1929_company.company_code = p1929_salesreport.company_code
SET p1929_salesreport.company_id = p1929_company.id;
/* after changes */
SELECT * FROM p1929_salesreport;
DROP TABLE p1929_salesreport;
DROP TABLE p1929_company;
Update with a join to your other table
UPDATE salesreport s
LEFT JOIN company c on s.company_code = c.company_code
SET s.company_id = c.id;
You could update using an inner join eg:
UPDATE salesreport s
INNER JOIN company c ON s.company_code = c.company_code
set s.company_id = c.id
MERGE into salesreport S
USING(select id, company_code, name from Company) C
ON(S.company_code=C.company_code)
WHEN MATCHED THEN
UPDATE
SET S.company_id = C.id
you can try this. this will update Salesreport table using company table when both company code matches.

Delete duplicate primary keys from a Mysql database using php programming

I have three fields in my database: first name, lastname and email. Email is my primary key. I don't have any other fields in my database.
I need to find a mysql query which can delete duplicated primary keys and their values from the database leaving only one unique email in the database.
I use the following command to display all duplicated primary keys. It worked, but I need to delete all other duplicate entries and keep only one. I am using php programming.
SELECT *
FROM table_name
WHERE primarykey IN (
SELECT primarykey
FROM table_name
GROUP BY primarykey
HAVING count(primarykey) > 1
)
ORDER BY primarykey
Populate a temp table with the ones you want to keep, using GROUP BY, HAVING and MAX on the other columns. Then run your query which deletes too much, then put your copied ones back in. And then make it the actual PK so it doesn't happen again.
You cannot do this with just 1 query, as you will need to use limit and that one needs to be set hard. (You cannot say limit someColumn for example.)
$query = "select primarykey, count(primarykey) as count from table_name group by primarykey having count(primarykey) > 1"
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$query = "delete from table_name where primarykey = ? limit " . $row['count'];
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $row['primarykey']);
$stmt->execute();
}
Email is not your primary key. Primary keys have a constraint on them where duplicates are not allowed. Your problem, by the way, is just an example of why you want to have an auto-incrementing numeric primary key on all tables. It seems too late for that.
One way to solve your problem is using temporary tables. The idea is to copy the data over, and tehn re-insert it:
create temporary table tmp_emails as
select email, firstname, lastname
from emails
group by email;
truncate table emails;
insert into emails(email, firstname, lastname)
select email, firstname, lastname
from tmp_emails;
Could you try this?
DELETE t1 FROM test t1, test t2
WHERE t1.email = t2.email
AND t1.fn > t2.fn
AND t1.ln > t2.ln;
Here are tests:
CREATE TABLE test
(
email varchar(100),
fn varchar(100),
ln varchar(100)
);
INSERT INTO test VALUES('a#b', 'f1', 'l1');
INSERT INTO test VALUES('a#b', 'f2', 'l2');
INSERT INTO test VALUES('c#d', 'f2', 'l2');
mysql> SELECT * FROM test;
+-------+------+------+
| email | fn | ln |
+-------+------+------+
| a#b | f1 | l1 |
| a#b | f2 | l2 |
| c#d | f2 | l2 |
+-------+------+------+
3 rows in set (0.00 sec)
mysql> DELETE t1 FROM test t1, test t2
-> WHERE t1.email = t2.email
-> AND t1.fn > t2.fn
-> AND t1.ln > t2.ln;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM test;
+-------+------+------+
| email | fn | ln |
+-------+------+------+
| a#b | f1 | l1 |
| c#d | f2 | l2 |
+-------+------+------+
2 rows in set (0.00 sec)
ALTER TABLE table_name RENAME TO table_name_bak;
CREATE TABLE table_name AS SELECT * FROM table_name_bak LIMIT 0;
ALTER TABLE table_name ADD PRIMARY KEY (email);
INSERT IGNORE INTO table_name SELECT * FROM table_name_bak;

MySQL - Count distinct number of name instances in database

A column in my table contains names. I created a query:
SELECT COUNT(*) Number, (b_concat_name) Name FROM `js_b_table` GROUP by Name
that produces the following:
Number | Name
1 | Chris Smith
4 | Fred Savage
2 | Sarah McArthur
How can I update the column b_name_count in js_b_table that contains the corresponding name (b_concat_name) in that row?
If I understand correctly, you want js_b_table to look something like this:
b_concat_name | b_name_count | ... other fields ...
--------------+--------------+---------------------
fred | 3 | ... other values ...
fred | 3 | ... other values ...
fred | 3 | ... other values ...
barney | 2 | ... other values ...
barney | 2 | ... other values ...
where every record's b_name_count indicates the total number of records with the same b_concat_name. Is that correct?
If so, you can use this:
UPDATE js_b_table AS jbt1
INNER
JOIN ( SELECT jbt2.b_concat_name,
COUNT(*) AS b_name_count
FROM js_b_table AS jbt2
GROUP
BY jbt2.b_concat_name
) AS jbt3
ON jbt3.b_concat_name = jbt1.b_concat_name
SET jbt1.b_name_count = jbt3.b_name_count
;
To get a count of how many time each name is in the table it's:
SELECT
count(*) AS number,
name
FROM USERS
GROUP BY name
If I understand correctly, you want to update a column, say name_count, for each user. You can do this by executing the following query:
UPDATE USERS u
SET u.name_count =
(SELECT count(*)
FROM USERS u2
WHERE u2.name = u.name);

Categories