INSERT INTO if condition is satisfied

痞子三分冷 提交于 2019-12-11 08:37:56

问题


I need to save the array $solution into the SQL table only if $solution[$i][0] belongs to the result of the query SELECT num_arr FROM Schedule WHERE num_arr<>''. If it does not belong to it, then the row $i must be not saved in the SQL table. The below-provided query seems to be incorrect. How do I implement the described task? What would be the correct approach to do this?

$query_land = "INSERT INTO `Sequence` (`num_arr`,`start`,`fin`,`way_id`) 
               VALUES ('".$solution[$i][0]."','".$solution[$i][1]."',
                                   '".$solution[$i][2]."','".$solution[$i][3]."') 
               WHERE '".$solution[$i][0]."' IN (SELECT num_arr 
                                                FROM Schedule 
                                                WHERE num_arr<>'')";

回答1:


The INSERT statment has two variations:

INSERT INTO tableX
    (a, b, c, ...)
VALUES
    (1, 2, 3, ...) ;

and

INSERT INTO tableX
    (a, b, c, ...)
SELECT
    1, 2, 3
FROM
    ... ;             --- the same or another table or many tables

The dual is a system table with exactly 1 row. It can be used for various things. Here it's used so a VALUES (...) is rewritten as a SELECT ... where we don't have any suitable table to put in the FROM clause:

$query_land = "INSERT INTO `Sequence` (`num_arr`,`start`,`fin`,`way_id`) 
               SELECT '".$solution[$i][0]."','".$solution[$i][1]."',
                      '".$solution[$i][2]."','".$solution[$i][3]."'
               FROM dual 
               WHERE '".$solution[$i][0]."' IN (SELECT num_arr 
                                                FROM Schedule 
                                                WHERE num_arr<>'')";


来源:https://stackoverflow.com/questions/12180259/insert-into-if-condition-is-satisfied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!