At-Sign in SQL statement before column name

前端 未结 1 753
醉梦人生
醉梦人生 2020-12-19 03:54

I have an INSERT statement in a PHP-file wherein at-signs (@) are occurring in front of the column name.

@field1, @field2,

It is a MySQL database. What do

1条回答
  •  無奈伤痛
    2020-12-19 04:11

    The @ sign is a variable in SQL.

    In MySQL it is used to store a value between consecutive runs of a query, or to transfer data between two different queries.

    An example

    Transfer data between two queries

    SELECT @biggest:= MAX(field1) FROM atable;
    SELECT * FROM bigger_table WHERE field1 > @biggest;
    

    Another usage is in ranking, which MySQL doesn't have native support for.

    Store a value for consecutive runs of a query

    INSERT INTO table2
      SELECT @rank := @rank + 1, table1.* FROM table1
      JOIN( SELECT @rank := 0 ) AS init
      ORDER BY number_of_users DESC
    

    Note that in order for this to work, the order in which the rows get processed in the query must be fixed, it's easy to get this wrong.

    See:
    http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
    mysql sorting and ranking statement
    http://www.xaprb.com/blog/2006/12/15/advanced-mysql-user-variable-techniques/

    UPDATE
    This code will never work.
    You've just opened the connection before and nowhere are the @fields set.
    So currently they hold null values.
    To top that, you cannot use @vars to denote fieldnames, you can only use @vars for values.

    $sql1 = "
    LOAD DATA LOCAL INFILE 'import.csv'
    REPLACE INTO TABLE tablename
    FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
    IGNORE 1 LINES
    (`normalField`, @field1, @field2, `normalField2`, @field3, @field4)";
    

    0 讨论(0)
提交回复
热议问题