Insert data using INSERT INTO command. - php

I have two table name users and users_images. Both table have the value of userId. like
My user table
| userId | userName | user_address |
| 2 | John | CN-2, UK |
| 3 | Amit | India |
| 4 | David | Us |
| 5 | Shan | Canada |
.
.
...... and so on
| 125000 | Naved | Ukran |
**and my images table contain userid and Image name.
Now I want to merge ImageName field to user table without using any loop (I want to do it with single query (I have millions of records and I will have to do it many times to create temorary table) )

update users u
set
u.imageName = (
select imageName
from users_images i
where i.userid = u.userid GROUP BY u.userId )

you could use ON DUPLICATE KEY
for instance:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;

I think you can use Update for this like:
UPDATE Users
SET ImageName =
(SELECT ImageName
FROM UserImages
WHERE UserImages.UserID = Uers.UserID)
Please take a backup of your database first

Related

How to compare data with another table's data before deleting the record in MySQL

I have this db called Enrolment where all the students will be added with batch and course. stud_id, course_id, and batch_id are referring to the other table with the fk.
enrolment
+----------+---------+-----------+----------+
| enrol_id | stud_id | course_id | batch_id |
+----------+---------+-----------+----------+
| 1 | 1 | 2 | 1 |
| 2 | 5 | 3 | 2 |
| 3 | 4 | 5 | 3 |
+----------+---------+-----------+----------+
Before I delete the student record in the student table, i want to compare the stud_id in the students table with the stud_id in the enrollment table. If it matches, do not delete the student. Or some kind of message to say this record is linked with the enrollment table, or something.
If it matches i want to run this $sql = "DELETE FROM students WHERE student_id = $id ";
students
+---------+------------+-----------+
| stud_id | first_name | last_name |
+---------+------------+-----------+
| 1 | John | Doe |
| 2 | Susy | Roberts |
| 3 | John | redneck |
+---------+------------+-----------+
Please help!!
It can be achieved using NOT IN
DELETE FROM students
WHERE student_id NOT IN (SELECT stud_id
FROM enrolment) AND student_id = $id
It can be achieved using NOT EXISTS
DELETE FROM students
WHERE NOT EXISTS(SELECT NULL
FROM enrolment
WHERE stud_id = $id) AND student_id = $id
you want to run a query like
$sql = SELECT COUNT(1) FROM enrolment WHERE stu_id = $id
Then check the contents for the number returned if > 0 then error.

MYSQL trigger to insert data into a row. based upon some criteria

I have three tables
purchase_master
+--------+---------+------------+
| autoid | user_id | package_id |
+--------+---------+------------+
user_master
+--------+---------+------+------------+-----------+
| autoid | user_id | name | user_email | user_pass |
+--------+---------+------+------------+-----------+
package_master
+-------------+----------+--------------+-----------+------------+---------------+------------+
| poster_path | overview | release_date | genre_ids | package_id | original_title| **isfree** |
+-------------+----------+--------------+-----------+------------+---------------+------------+
I want that whenever a new row is created into user_master, a trigger should fire that gets all rows in package_master where isfree = true, and populate those records along with new user_master.user_id into purchase_master table.
Example
lets say package_master has 2 rows having package_id = 100 & package_id = 101, in which isfree=true so when a new record is created into user_master having user_id = C601, the purchase_master table should have 2 new entries like.
"autoid" = 10,"user_id"=C601,"package_id"=100
"autoid" = 11,"user_id"=C601,"package_id"=101
Please guide me if it is possible through mysql trigger. Else I have to do it in PHP, on form submission.
EDIT:: I am using phpmyadmin
Try something like this:
CREATE TRIGGER bi_user_master BEFORE INSERT ON user_master
INSERT INTO purchase_master (user_id, package_id)
SELECT NEW.user_id, pm.package_id
FROM package_master AS pm
WHERE isfree;

MySQL populating field based on another table using LIKE match

I know it's not the cleanest code to date, but I can't figure out why I can't get this one to work.
I'm looking to populate the field m.customersTemp with Customer Numbers from field c.ClientNumber. But only when a LIKE match from c.EmailAddress is found m.Emails... m.Emails is a field with a list of e-mails. Code Below.
UPDATE market m, customer c
SET m.customersTemp = CONCAT(m.customersTemp, c.ClientNumber)
WHERE m.Emails LIKE CONCAT('%', TRIM(c.EMailAddress), '%')
AND TRIM(c.EMailAddress)<>''
The result in field m.customersTemp only displays one value (customer number)... and I know there are many matches.
TABLE CUSTOMER
ClientNumber | EMailAddress
1234 a#a.com
4567 b#b.com
2222
1111 d#d.com
-------------------------------------------------------------
| TABLE MARKET |
-------------------------------------------------------------
| ID | Emails | customersTemp|
-------------------------------------------------------------
|1 | a#a.com, b#b.com, c#c.com | |
|2 | a#a.com, b#b.com, g#g.com | |
|3 | e#e.com | |
|4 | f#f.com | |
-------------------------------------------------------------
Result in customersTemp at ID 1 and 2 is only 1 ClientNumber. 4567
Don't forget to read the Warning at the bottom as to why you should NEVER save your data like this.
You can test this on a backup copy. I wouldn't run it against your main tables. Akin to someone saying: "Here, try this delete command, I think it will work."
-- drop table customer;
create table customer
( ClientNumber int,
EMailAddress varchar(100)
);
insert customer (ClientNumber,EMailAddress) values
(1234,'john#john.com'),
(4567,'joe#joe.com'),
(2222,''),
(1111,'somone#someone.com'),
(5454,'john#john.com');
-- drop table market;
create table market
( Emails varchar(100),
customersTemp varchar(100)
);
insert market(Emails,customersTemp) values
('john#john.com',''),
('joe#joe.com',''),
('test#test.com',''),
('more#more.com','');
The Update statement:
UPDATE market
INNER JOIN
( SELECT c.EMailAddress as e,GROUP_CONCAT(c.ClientNumber ORDER BY c.ClientNumber) theList
FROM customer c
GROUP BY c.EMailAddress
) xDerived1
ON market.EMails = xDerived1.e
SET market.customersTemp = xDerived1.theList;
Results:
select * from market;
+---------------+---------------+
| Emails | customersTemp |
+---------------+---------------+
| john#john.com | 1234,5454 |
| joe#joe.com | 4567 |
| test#test.com | |
| more#more.com | |
+---------------+---------------+
Version2
drop table customer;
create table customer
( ClientNumber int,
EMailAddress varchar(100)
);
insert customer (ClientNumber,EMailAddress) values
(1234,'a#a.com'),
(4567,'b#b.com'),
(2222,''),
(1111,'d#d.com'),
(8484,'g#g.com');
-- select * from customer;
drop table market;
create table market
( id int auto_increment primary key,
Emails varchar(100),
customersTemp varchar(3000)
);
insert market(Emails,customersTemp) values
('a#a.com,b#b.com,c#c.com',''),
('a#a.com,b#b.com,g#g.com',''),
('e#e.com',''),
('f#f.com','');
-- select * from market;
drop table if exists marketHelper7;
create table marketHelper7
( -- btw this might be the kind of table
-- as an intersect/junction table that you
-- should have to begin with
-- and not have your CSV stuff
cid int not null,
mid int not null
);
insert marketHelper7 (cid,mid)
select c.ClientNumber,m.id as MarketId
from customer c
join market m
on find_in_set(c.EMailAddress,m.Emails)>0;
update market set customersTemp=''; -- do a reset
UPDATE market m
join
( SELECT mh.mid as i,GROUP_CONCAT(mh.cid ORDER BY mh.cid) theList
FROM marketHelper7 mh
GROUP BY mh.mid
) xDerived1
ON m.id = xDerived1.i
SET m.customersTemp = xDerived1.theList;
drop table marketHelper7;
.
select * from market;
+----+-------------------------+----------------+
| id | Emails | customersTemp |
+----+-------------------------+----------------+
| 1 | a#a.com,b#b.com,c#c.com | 1234,4567 |
| 2 | a#a.com,b#b.com,g#g.com | 1234,4567,8484 |
| 3 | e#e.com | |
| 4 | f#f.com | |
+----+-------------------------+----------------+
Version 2 above has the helper table.
Warning:
By the way, never save your data like this. It is insane, and the performance is awful. Please see my answer here on Junction Tables (many-to-many) (similar to association tables or "item has" tables a.k.a. One-to-Many). They are all the same concept that utilized Data Normalization best practices and fast indexes during queries. Plus you stay happier not fighting with your data constantly or wondering if you blow the buffer size with group_concat.
Note that group_concat() has flexibility for its separator choice, and the order by, baked inside the function call.
The maximum length for the output of group_concat is subject to the system variable group_concat_max_len which probably defaults to 1K but can be set to at least 4GB.
The Percona article on group_concat(), and the manual pages for group_concat() and find_in_set().

i want to retrieve unique values from my table

In a table i have some of column have duplicate values i want to retrieve unique values from my table i used SELECT DISTINCT column_name FROM table_name query and i got unique columns but my problem is i also want id of anyone of the duplicate value how can i retrieve that from using a single query ?
Eg
+----+------+------+
| id | name | po |
+----+------+------+
| 1 | some | 2 |
| 2 | xyzs | 3 |
| 3 | frth | 2 |
| 4 | lopd | 3 |
| 5 | gtry | 2 |
+----+------+------+
i want to find unique po and any one of its id
Output
some thing like this
po - 2 id - ( any of 1,3,5)
po - 3 id - ( any of 2 or 4)
Just group them and get the max id or the min.
SELECT max(id), po FROM table_name group by po
try this:
SELECT MIN(id) id, po
FROM table_name
GROUPB BY po, id
Don't quote me on this, but you might be able to do something like:
SELECT GROUP_CONCAT(id) FROM table_name GROUP BY po
If you don't care which id you will get, then:
SELECT po,id FROM table GROUP BY po
If you wish to get first/last of the ids with that same po, you can add MIN(id)/MAX(id) as well:
SELECT po,MIN(id) as id FROM table GROUP BY po
You can also have all the ids for that po:
SELECT po,GROUP_CONCAT(id) as ids FROM table GROUP BY po

Show database entries separated by comma

I have one field in the backend, where I input IDs separated by comma - ID1, ID2, ID3....These are videos in fact. All ids are stored in the field product_videos in the database (as they are typed).
How can I echo these id's on the frontend so they all show for the product?
Storing comma separated data in one data field is a bad idea. It is a real pain to manipulate, so you should really consider revising your db structure.
You haven't shown your data structure, so I'll give a basic example and then explain how it can be improved. My example assumes product_videos is linked to particular users:
table: `users`
| user_id | user_name | product_videos |
|---------|-----------|----------------|
| 1 | User1 | 1,2,3,4,6,7 |
| 2 | User2 | 5 |
You would maybe run a query
SELECT `product_videos` FROM `users` WHERE `user_name` = 'User1'
This would give you one row, with a comma separate value - you would then need to use something like PHP's explode() to convert it into an array and then loop through that array. That is a very bad method (and it will only become harder as you try to do more advanced things).
Instead, it would be easier to use a link table. Imagine:
table: `users`
| user_id | user_name |
|---------|-----------|
| 1 | User1 |
| 2 | User2 |
table: `videos`
| video_id | user_id |
|-----------|---------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 1 |
| 7 | 1 |
In this example, each video is a separate row in a db table (and each video is linked to an existing user). Each row is readily able to be handled independently. This makes it really easy to handle extra data for each video, such as a title, runtime length, date of uploading, etc.
You would then need to run a JOIN query. e.g.
SELECT `videos`.`video_id` FROM `videos`
INNER JOIN `users` ON `users`.`user_id` = `videos`.`user_id`
WHERE `users`.`user_name` = 'User1'
In PHP, you would do something like:
$q = mysql_query("SELECT `videos`.`video_id` FROM `videos` INNER JOIN `users` ON `users`.`user_id` = `videos`.`user_id` WHERE `users`.`user_name` = 'User1'");
while ($row = mysql_fetch_assoc($q)) {
echo "VIDEO ID = " . $row["video_id"] . "<br/>";
}

Categories