Jens
Jens

Reputation: 291

How insert data from foreign key of another table?

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?

Upvotes: 1

Views: 394

Answers (2)

Robin Choffardet
Robin Choffardet

Reputation: 460

Do you mean something like this ? :

INSERT INTO LOGS VALUES(NULL, (SELECT query_type_id FROM QUERYTYPES WHERE query_type = 'your_query_type_here'))

Upvotes: 0

Barmar
Barmar

Reputation: 780713

You use a SELECT query instead of VALUES

INSERT INTO LOGS (query_type)
SELECT query_type_id
FROM QUERYTYPES

Upvotes: 1

Related Questions