MySQL CONCAT没有找到带别名的表

时间:2017-05-30 17:54:53

标签: mysql concatenation concat

我有一个相当直接的查询,我不明白为什么CONCAT无效。

JOININGdomains client_contentdomain_status并尝试insert into vhosts。在我使用CONCAT组合domain_status.status_directoryclient_configuration.user_file之前,所有工作都按预期进行。此时是我指定的范围之外的别名吗?

                      ----------------------------------------
domains               |  domain   |   enabled   |   status   |
                      ----------------------------------------

                      -------------------------------------
client_configuration  |   contractor_id   |   user_file   |
                      -------------------------------------

                      ---------------------------------
domain_status         |   id   |   status_directory   |
                      ---------------------------------

                      ------------------------------------------------------------
vhosts                |   site_name   |   directory   |   enabled   |   status   |
                      ------------------------------------------------------------


INSERT INTO vhosts (`site_name`, `directory`, `enabled`, `status`)
    SELECT d.domain, CONCAT(`s.status_directory`,'/',`c.user_file`), d.enabled, d.status  
    FROM domains d

    LEFT JOIN client_configuration c
        ON d.contractor_id = c.contractor_id
    LEFT JOIN domains_status s
        ON d.status = s.id
    WHERE d.domain = 'example.com';

根据我的理解,我应该能够以这种方式使用CONCAT,但我收到MySQL错误:

Error Code: 1054. Unknown column 's.status_directory' in 'field list'

如果我不能像这样使用CONCAT ..什么是解决方法?

2 个答案:

答案 0 :(得分:1)

问题在于,您使用与列名称相同的反引号来包围表别名。从这些引号中取出表别名。试试这个:

INSERT INTO vhosts 
(
  `site_name`, 
  `directory`, 
  `enabled`, 
  `status`
)
SELECT 
  d.domain, 
  CONCAT(s.`status_directory`,'/', c.`user_file`), 
  d.enabled, 
  d.status  
FROM domains d
LEFT JOIN client_configuration c
  ON d.contractor_id = c.contractor_id
LEFT JOIN domains_status s
  ON d.status = s.id
WHERE d.domain = 'example.com';

答案 1 :(得分:0)

删除引号:INSERT INTO vhosts (site_name, directory, enabled, status) SELECT d.domain, CONCAT(s.status_directory,'/',c.user_file) as statusUserFile, d.enabled, d.status FROM domains d LEFT JOIN client_configuration c ON d.contractor_id = c.contractor_id LEFT JOIN domains_status s ON d.status = s.id WHERE d.domain = 'example.com';