2014-01-27 43 views
0

我有问题,从两个表中选择,左连接到第三个。查询:mysql从两个表中选择和左连接

SELECT 
    c.id AS currency, u.user, us.enabled AS currency 
FROM 
    users AS u, 
    currency AS c 
    LEFT JOIN users_settings AS us ON(c.id=us.currency, u.user=us.user) 
WHERE 
    c.off=0 AND c.disabled=0 AND c.status=1 

错误:

#1054 - Unknown column 'u.user' in 'field list'

我需要的用户和货币的笛卡尔乘积。 用户:ID,登录,电子邮件,通过

http://en.wikipedia.org/wiki/Cartesian_product

+0

你能向我们展示用户表吗? – James

+0

不要使用逗号连接语法,并且绝对不要混合使用逗号连接和显式连接语法,直到您真正知道自己在做什么为止。 – Strawberry

+0

我需要用户和货币的笛卡尔积。用户:身份证,登录,电子邮件,通过http://en.wikipedia.org/wiki/Cartesian_product – Sannin

回答

1

你混合显性和隐性的连接语法。试试这个:

SELECT c.id AS currency, u.user, us.enabled AS currency 
FROM currency AS c LEFT JOIN 
    users_settings AS us 
    ON c.id = us.currency LEFT JOIN 
    users u 
    on u.user = us.user 
WHERE c.off = 0 AND c.disabled = 0 AND c.status = 1 ; 

MySQL不一定允许通过,知道这些字段。范围界定是,cross join之间的区别之一。不过,无论如何,您应该为每个join单独使用on子句。

这里是在documentation说明:

INNER JOIN and , (comma) are semantically equivalent in the absence of a join condition: both produce a Cartesian product between the specified tables (that is, each and every row in the first table is joined to each and every row in the second table).

However, the precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form Unknown column 'col_name' in 'on clause' may occur. Information about dealing with this problem is given later in this section.

,而不是试图真正理解这是什么意思,只是避免from子句中使用,。这不是必需的。

+0

谢谢,但这不是笛卡尔产品http://en.wikipedia.org/wiki/Cartesian_product – Sannin

+1

@Sannin。 。 。除了作用域规则外,'''在语义上等同于'交叉连接'。两者都创建笛卡尔产品而无需额外过滤。但是,关键是使用','的语法会导致查询出现问题。 –