0

我在 MySQL 5.5 中写一个视图。我的代码如下:

  DROP VIEW IF EXISTS vw_lancamentos;
  CREATE VIEW vw_lancamentos AS
  SELECT
    l.id,
    l.data_hora_lancamento,
    l.valor,
    l.descricao,
    l.veiculo_id,
    l.plano_conta_id,
    pc.id,
    pc.master_id,
    pc.descricao,
    pc.tipo_movimento
  FROM
    lancamentos l, plano_de_contas pc
  LEFT JOIN
    plano_de_contas on (l.plano_conta_id = pc.id);

当我尝试编译上面的代码时,服务器返回此错误: 错误代码:1054。“on 子句”中的未知列“l.plano_conta_id”

我怎样才能让它工作?我以前使用过 Firebird,我可以看到它与 MySQL 完全不同。

4

2 回答 2

4

您的JOIN语法错误,并且您有两列同名。如果您想同时返回两者l.idpc.id那么您将需要为这两个区分它们的字段提供别名:

CREATE VIEW vw_lancamentos AS
  SELECT
    l.id as l_id,  --  add alias
    l.data_hora_lancamento,
    l.valor,
    l.descricao,
    l.veiculo_id,
    l.plano_conta_id,
    pc.id as pc_id, --  add alias
    pc.master_id,
    pc.descricao,
    pc.tipo_movimento
  FROM lancamentos l
  LEFT JOIN plano_de_contas pc
     on l.plano_conta_id = pc.id;
于 2013-01-09T14:41:01.080 回答
2

Please try this...sorry igonore my comment, I just noticed how you are doing the LEFT JOIN. The way arrange the join Syntax is wrong...

....

 FROM lancamentos l
 LEFT JOIN
 plano_de_contas pc on (l.plano_conta_id = pc.id);

EDIT AS PER OP'S COMMENT:

in your select query you are selecting thtese...both the same... so to recorrect the reasoning, you need to add alias to one.

    l.id,
    pc.id as pcid,

EDIT:

  • SQLFIDDLE DEMO : it's sufficient to provide alias to one column out of the two that has the same name/duplicate name...
于 2013-01-09T14:30:43.863 回答