Sql如何在Select中增加一个字段

时间:2017-08-23 14:07:45

标签: mysql

我尝试从简单的SELECT创建视图。

SELECT NULL AS productcode
       , name 
  FROM item;

productcode    name
NULL           Toto
NULL           Titi
NULL           Tata

而不是null我想从另一个表中获取我的产品代码(9000)并将其递增以获得:

 productcode    name
 90001           Toto
 90002           Titi
 90003           Tata

谢谢

1 个答案:

答案 0 :(得分:0)

如果我理解了您的问题,您可以尝试处理类似这样的查询:

CREATE TABLE P (product_code VARCHAR(10), NAME VARCHAR(10));
CREATE TABLE U (product_code VARCHAR(10));

INSERT INTO P VALUES (NULL,'Toto');
INSERT INTO P VALUES (NULL,'Titi');
INSERT INTO P VALUES (NULL,'Tata');
INSERT INTO P VALUES (1,'Prod1');

INSERT INTO U VALUES ('90000');  #THIS MUST HAVE ONLY ONE RECORD!


SELECT NEW_CODE, NAME 
FROM (
    SELECT P.NAME
    , @r:= @r+1 R
    , CONCAT(U.product_code,@r) NEW_CODE 
    FROM P 
    CROSS JOIN (SELECT @r:=0) C
    CROSS JOIN U 
    WHERE P.product_code IS NULL
    ) Y;

输出:

    NEW_CODE    NAME
1   900001  Toto
2   900002  Titi
3   900003  Tata