USING MS SQL-SERVER
I wanted to know if it was possible or better said the most efficient way to insert values into a table where one of the values inserted is dependent on another table, and if that Select query is not existent on the other table it would not do it.
for example the next query
INSERT INTO producto VALUES
('ad-101', '27', 'Nissan','NP300','2016','aer3457','1',(SELECT Id from Inventario WHERE Serie = '5161017293')),
('ad-102', '27', 'Nissan','NP300','2015','aer5647','1',(SELECT Id from Inventario WHERE Serie = '5161019329'))
If 5161019329
was not on the table Invetory only 1 row was inserted.
i know i can always do a seperate query for the select part and afterwards do my logic on php to insert it or not, but that's not that efficent since sometimes i can have 100 rows inserted at once.
Thanks,
PDO has a rowCount() function that can be called to count the amount of rows that the query you have made has, if that is what you mean. (The question didn't really make sense)
You could try:
$query = $handler->query("Your select query");
if ($query->rowCount() == 0) {
// Insert Query
}
Other than that I haven't used the MySQLi connection much but you could loop the query with a $count++
variable started at 0, then if that $count
variable is equal to 0 then insert the query later on in the logic.
Sorry if the answer doesn't make sense but the question didn't either.
If the column that ID number your select returns is not a nullable column mysql should prevent the insert and throw an error.
You can use the following query, it should work
INSERT INTO producto
SELECT
'ad-101', '27', 'Nissan','NP300','2016','aer3457','1', Id FROM Inventario WHERE Serie = '5161017293'
If there is no row in Incentario
with Serie
5161017293, no data will be inserted.