MySQL Insertar Donde consulta


Qué hay de malo en esta consulta:

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Funciona sin la cláusula WHERE. Parece que olvidé mi SQL..

 96
Author: Taryn, 2009-01-27

24 answers

MySQL INSERT Syntax no admite la cláusula WHERE, por lo que su consulta tal como está fallará. Suponiendo que su columna id es única o clave primaria:

Si está tratando de insertar una nueva fila con ID 1, debe usar:

INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);

Si está tratando de cambiar los valores de peso / peso deseado para una fila existente con ID 1, debe usar:

UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;

Si lo desea, también puede usar INSERT .. EN la sintaxis de CLAVE DUPLICADA como así:

INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

O incluso como entonces:

INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

También es importante tener en cuenta que si su columna id es una columna de autoincremento, entonces también podría omitirla de su INSERTAR todos juntos y dejar que mysql la incremente como es normal.

 197
Author: Chad Birch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-08 20:15:16

No se puede combinar una cláusula WHERE con una cláusula VALUES. Usted tiene dos opciones por lo que yo sé-

  1. INSÉRTESE especificando valores

    INSERT INTO Users(weight, desiredWeight) 
    VALUES (160,145)
    
  2. INSERTAR usando una instrucción SELECT

    INSERT INTO Users(weight, desiredWeight) 
    SELECT weight, desiredWeight 
    FROM AnotherTable 
    WHERE id = 1
    
 33
Author: Russ Cam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-02 10:37:18

Se utiliza la cláusula WHERE para las consultas de ACTUALIZACIÓN. Cuando INSERTA, está asumiendo que la fila no existe.

En MySQL, si desea INSERTAR o ACTUALIZAR, puede usar la consulta REEMPLAZAR con una cláusula WHERE. Si el DÓNDE no existe, se INSERTA, de lo contrario se ACTUALIZA.

EDITAR

Creo que el punto de Bill Karwin es lo suficientemente importante como para sacarlo de los comentarios y hacerlo muy obvio. Gracias Bill, ha pasado demasiado tiempo desde que he trabajado con MySQL, recordé que tenía problemas con REEMPLAZAR, pero olvidé cuáles eran. Debería haberlo buscado.

Así no es como funciona el REEMPLAZO de MySQL. Hace un DELETE (que puede ser un no-op si la fila no existe), seguido de un INSERT. Piense en las consecuencias vis. disparadores y dependencias de claves foráneas. En su lugar, utilice INSERTAR...EN LA ACTUALIZACIÓN DE CLAVES DUPLICADAS.

 19
Author: Rob Prouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-27 22:00:52

No creo que el inserto tenga una cláusula WHERE.

 7
Author: Daniel A. White,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-27 20:17:11

Insertar consulta no es compatible con la palabra clave *

Se aplican condiciones porque puede usar la condición where para las instrucciones de sub-selección. Puede realizar inserciones complicadas utilizando sub-selecciones.

Por ejemplo:

INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';

Al colocar un "select" en la instrucción insert, puede realizar inserciones múltiples rápidamente.

Con este tipo de inserción, es posible que desee comprobar el número de filas que se insertan. Puede determinar el número de filas que se insertarán ejecutando la siguiente instrucción SQL antes de realizar la inserción.

SELECT count(*)
FROM customers
WHERE city = 'Newark';

Puede asegurarse de no insertar información duplicada utilizando la condición EXISTS.

Por ejemplo, si tuviera una tabla llamada clients con una clave primaria de client_id, podría usar la siguiente instrucción:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);

Esta instrucción inserta varios registros con una subselección.

Si desea insertar un solo registro, puede usar la siguiente instrucción:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);

El uso de la dual table le permite introducir sus valores en una instrucción select, aunque los valores no estén almacenados actualmente en una tabla.

Véase también Cómo insertar la cláusula where

 5
Author: Somnath Muluk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:12

La respuesta correcta a esta pregunta será así:

A). SI desea seleccionar antes insertar:

INSERT INTO Users( weight, desiredWeight ) 
  select val1 , val2  from tableXShoulatNotBeUsers
  WHERE somecondition;

B). SI el registro ya existe, use update en lugar de insert:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Debe ser

Update Users set weight=160, desiredWeight=145  WHERE id = 1;

C). Si desea actualizar o insertar al mismo tiempo

Replace Users set weight=160, desiredWeight=145  WHERE id = 1;

Note):- you should provide values to all fields else missed field in query 
        will be set to null

D). Si desea CLONAR un registro de LA MISMA tabla, solo recuerde que no puede seleccionar de la tabla a la que está insertando por lo tanto

 create temporary table xtable ( weight int(11), desiredWeight int(11) ;

 insert into xtable (weight, desiredWeight) 
    select weight, desiredWeight from Users where [condition]

 insert into Users (weight, desiredWeight) 
    select weight , desiredWeight from xtable;

Creo que este bonito cubre la mayor parte de la escenarios

 4
Author: sakhunzai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-06 10:38:48

Insert into = Agregar filas a una tabla

Upate = actualizar filas específicas.

¿Qué describiría la cláusula where en su inserción? No tiene nada que coincidir, la fila no existe (todavía)...

 2
Author: Richard L,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-27 20:20:41

Simplemente no puede usar WHERE al hacer una instrucción INSERT:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Debe ser:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );

La parte WHERE solo funciona en las instrucciones SELECT:

SELECT from Users WHERE id = 1;

O en declaraciones de ACTUALIZACIÓN:

UPDATE Users set (weight = 160, desiredWeight = 145) WHERE id = 1;
 2
Author: Borniet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-09 12:43:49

LEE ESTO TAMBIÉN

No tiene sentido... incluso literalmente

INSERT significa agregar un new row y cuando dices WHERE defines de qué fila estás hablando en el SQL.

Por lo tanto, agregar una nueva fila no es posible con una condición en una fila existente.

Tienes que elegir entre lo siguiente:

A. Use UPDATE en lugar de INSERT

B. Use INSERT y elimine la cláusula WHERE (solo lo estoy diciendo...) o si usted está realmente obligado a use INSERT y WHERE en una sola instrucción solo se puede hacer mediante INSERT..SELECT clause ...

INSERT INTO Users( weight, desiredWeight ) 
SELECT FROM Users WHERE id = 1;

Pero esto sirve para un propósito completamente diferente y si ha definido id como Clave Primaria, esta inserción será un error, de lo contrario se insertará una nueva fila con id = 1.

 2
Author: SiB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 08:48:09

Depende de la situación INSERTAR puede tener realmente una cláusula where.

Por ejemplo, si coincide con valores de un formulario.

Consider INSERT INTO Users(name,email,weight, desiredWeight) VALUES (fred,[email protected],160,145) WHERE name != fred AND email != [email protected]

Tiene sentido ¿no?

 1
Author: Frank Nwoko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-15 20:23:19

La forma más sencilla es usar IF para violar su restricción de clave a. Esto solo funciona para INSERTAR IGNORAR, pero le permitirá usar restricción en una INSERCIÓN.

INSERT INTO Test (id, name) VALUES (IF(1!=0,NULL,1),'Test');
 1
Author: Ethan Brooks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-06 22:42:26

Después de la cláusula WHERE se pone una condición, y se usa para obtener datos o para actualizar una fila. Al insertar datos, se asume que la fila no existe.

Entonces, la pregunta es, ¿hay alguna fila cuyo id es 1? si es así, use MySQL UPDATE, de lo contrario use MySQL INSERT.

 1
Author: Revathi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-14 06:55:41

Si está especificando un registro particular no para insertar datos, es mejor usar la instrucción UPDATE en lugar de la instrucción INSERT.

Este tipo de consulta que ha escrito en la pregunta es como una consulta ficticia.

Su consulta es: -

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Aquí, está especificando el id = 1, por lo que es mejor que use la instrucción UPDATE para actualizar record.It no se recomienda utilizar la cláusula WHERE en el caso de INSERT.Debe usar UPDATE .

Ahora Usando la Consulta de Actualización: -

UPDATE Users SET weight=160,desiredWeight=145 WHERE id=1;
 1
Author: Java Developers Guide,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-07 05:28:17

Hace WHERE-clause se puede usar realmente con INSERT-INTO-VALUES en cualquier ¿case?

La respuesta es definitivamente no.

Añadiendo una cláusula WHERE después de INSERT INTO ... VALOR ... es solo SQL inválido, y no analizará.

El error devuelto por MySQL es:

mysql> INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 1

La parte más importante del mensaje de error es

... syntax to use near 'WHERE id = 1' ...

Que muestra la parte específica que el analizador no esperaba encontrar aquí: la cláusula WHERE.

 1
Author: Marc Alff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-07 19:37:25

Está totalmente equivocado. INSERT QUERY no tiene una cláusula WHERE, Solo UPDATE QUERY la tiene. Si desea agregar datos donde id = 1, su consulta será

UPDATE Users SET weight=160, desiredWeight= 145 WHERE id = 1;
 1
Author: Gurria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-10 10:39:01

No. Por lo que sé, no puede agregar la cláusula WHERE en esta consulta. Tal vez he olvidado mi SQL también, porque no estoy muy seguro de por qué lo necesita de todos modos.

 1
Author: Ikechi Anyanwu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 05:14:17

No debe usar where condition en la instrucción Insert. Si lo desea, utilice insert in a update statement y, a continuación, actualice un registro existente.

¿Realmente puedo saber por qué necesita una cláusula where en la instrucción Insert??

Tal vez basado en la razón por la que podría sugerirte una mejor opción.

 1
Author: Krishna Thota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 06:01:28

Creo que su mejor opción es usar REEMPLAZAR en lugar INSERTAR

REEMPLAZAR EN Users (id, weight, desiredWeight) VALORES(1, 160, 145);

 1
Author: Alberto León,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 08:03:16

Puede hacer INSERCIONES condicionales basadas en la entrada del usuario. Esta consulta se insertará solo si los vars de entrada 'us userWeight 'y' us userDesiredWeight ' no están en blanco

INSERT INTO Users(weight, desiredWeight )
select '$userWeight', '$userDesiredWeight'  
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
 1
Author: Igor Vujovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 12:23:05

Soy consciente de que este es un post antiguo, pero espero que esto siga ayudando a alguien, con lo que espero que sea un ejemplo simple:

Antecedentes:

Tenía un caso de muchos a muchos: el mismo usuario aparece varias veces con múltiples valores y quería crear un nuevo registro, por lo tanto, la ACTUALIZACIÓN no tendría sentido en mi caso y necesitaba dirigirme a un usuario en particular como lo haría usando una cláusula WHERE.

INSERT into MyTable(aUser,aCar)
value(User123,Mini)

Al usar esta construcción, realmente se dirige a un usuario específico (user123, que tiene otros registros) así que realmente no necesitas una cláusula where, supongo.

La salida podría ser:

aUser   aCar
user123 mini
user123 HisOtherCarThatWasThereBefore
 1
Author: Ylenia88m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 15:19:16

La sintaxis correcta para mysql insert into statement usando el método post es:

$sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";
 0
Author: chaitanya koripella,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-27 17:10:37

No creo que podamos usar la cláusula where en la instrucción insert

 0
Author: Nipun Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-04 12:00:33
INSERT INTO Users(weight, desiredWeight )
SELECT '$userWeight', '$userDesiredWeight'  
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
 0
Author: user6297694,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-05 22:15:59

No puedes usar INSERT y WHERE juntos. Puede usar la cláusula UPDATE para agregar valor a una columna en particular en un campo particular como el siguiente código;

UPDATE Users
SET weight='160',desiredWeight ='145'  
WHERE id =1
 0
Author: Vishal Vaishnav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 06:00:52