从2个表中选择。 MySQL的

时间:2009-09-25 15:42:54

标签: mysql sql mysql-error-1054

如何在不写长姓的情况下选择p.Quota?现在我正在做

SELECT c.id, 
       c.UserName, 
       p.Quota, 
       cs.StatusName 
  FROM CUSTOMERS AS c, 
       PRODUCTS AS p 
 LEFT JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId=cs.CustomerStatusId 
 LIMIT 1 ;

我收到错误:

ERROR 1054 (42S22): Unknown column 'c.StatusId' in 'on clause'

但是该列确实退出并且此代码有效:

SELECT c.id, 
       c.UserName, 
       cs.StatusName 
  FROM CUSTOMERS AS c
  JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId = cs.CustomerStatusId 
 LIMIT 1 ;

3 个答案:

答案 0 :(得分:2)

您将ANSI和非ANSI JOIN语法混合为:

SELECT c.id, 
       c.UserName, 
       p.Quota, 
       cs.StatusName 
  FROM CUSTOMERS AS c, 
       PRODUCTS AS p 
  LEFT JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId=cs.CustomerStatusId 
  LIMIT 1 ;

使用ANSI连接编写:

     SELECT c.id, 
            c.UserName, 
            p.Quota, 
            cs.StatusName 
       FROM CUSTOMERS AS c 
       JOIN PRODUCTS AS p ON --JOIN criteria goes here
  LEFT JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId = cs.CustomerStatusId 
      LIMIT 1;

...但我不知道您使用PRODUCTS加入CUSTOMERS表的标准。

答案 1 :(得分:2)

问题是你的隐式内连接后跟左连接。 MySQL正在尝试在CUSTOMERSTATUSTYPES cs上加入PRODUCTS p,而不考虑CUSTOMERS c。

试试这个:

SELECT 
 c.id, c.UserName, p.Quota, cs.StatusName 
FROM 
 CUSTOMERS AS c 
 INNER JOIN PRODUCTS AS p 
 LEFT JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId=cs.CustomerStatusId 
LIMIT 1 

此外,现在您没有任何条款将CUSTOMERS中的记录与产品中的记录相关联......您只是在进行全面加入。这是你想要做的吗?

答案 2 :(得分:0)

SELECT c.id, 
       c.UserName, 
       p.Quota, 
       cs.StatusName 
FROM (CUSTOMERS AS c, PRODUCTS AS p) 
LEFT JOIN CUSTOMERSTATUSTYPES as cs ON c.StatusId=cs.CustomerStatusId 
LIMIT 1 ;