How insert data from foreign key of another table? - php

I've got a txt file with many rows. I insert data from every row into db.
foreach (... => ...) {
...
$types = new QueryTypes();
$types->query_type = $prepared_data_from_file;
$types->save();
$logs = new Logs();
$logs->query_type = ...
...
}
-----------------------------------------------------
| LOGS |
-----------------------------------------------------
| log_id (PK) | query_type (FK from query_type_id) |
-----------------------------------------------------
---------------------------------
| QUERYTYPES |
---------------------------------
|query_type_id (PK)| query_type |
---------------------------------
I need something like
INSERT INTO LOGS(query_type) VALUES (SELECT query_type_id FROM QUERYTYPES)
How could I insert column query_type_id from QUERYTYPES into column query_type in LOGS in yii2?

You use a SELECT query instead of VALUES
INSERT INTO LOGS (query_type)
SELECT query_type_id
FROM QUERYTYPES

Do you mean something like this ? :
INSERT INTO LOGS VALUES(NULL, (SELECT query_type_id FROM QUERYTYPES WHERE query_type = 'your_query_type_here'))

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

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;

PHP - how to create some column/field depending on another row table

there's some way to create column depending by another row?
I mean like this :
example:
I have table A:
|----|----------|
| id | criteria |
|----|----------|
| 1 | column A |
| 2 | column B |
| 3 | column C |
| .. | ... |//column D, E, F, etc
|----|----------|
how to create a Table B like this?
|column A |column B |column C | ... |
|---------|---------|---------|-----|
| value | value | value |(etc)|
| ... | ... | ... | ... |
|---------|---------|---------|-----|
is it possible with PHP??
I don't know a keyword of this case, so if someone wanna give me a link, it would be appreciate
You can get Criteria from Table A by SELECt query, Assume that you know the SELECT Query, and after that based on result You can run loop for each Criteria get from table A. and for add column Use below query.
IF NOT EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tablename'
AND table_schema = 'db_name'
AND column_name = 'columnname') THEN
ALTER TABLE `TableName` ADD `ColumnName` varchar(255) ;
END IF;

Insert data using INSERT INTO command.

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

How to find last inserted varchar value in a table using MySQL query

I have a table student, table structure is follow
student_id | name | class|
-------------------------
2-12-2013 | test | 3 |
-------------------------
2-13-2013 |test2 | 5 |
-------------------------
in this table i want add new record, its student_id become 2-14-2013. For that i want to get the last inserted student_id. how can i get it by MySQL query. Am alredy use mysql_insert_id() But its not working, How to solve this issue?
Define Your student table like below:-
student_id | add_date | name | class|
--------------------------------------
1 | 2013-12-2 | test | 3 |
--------------------------------------
2 | 2013-13-2 |test2 | 5 |
--------------------------------------
student_id would be int auto increamented primary key
then execute Query like below to get last inserted id:-
select student_id from student order by student_id desc limit 1;
Hi You has to set primary key to your table as integer auto-increment then you can use this last inserted id
$con = mysql_connect("localhost", "root", "", "chirag2");
$sql = "INSERT INTO test_student ( student_id,name,class)values('3-12-2013','test1','3' )";
$res = mysql_query($con, $sql);
echo mysql_insert_id($con);
die;
Note: you need to truncate table before alter it and set new primary key to it so take backup before this

Categories