1

我有以下查询:

SELECT * FROM questions 
LEFT JOIN answers ON (questions.id = answers.id AND (connections.username = answers.username OR connections.username = 'bob' OR answers.username IS NULL))
LEFT JOIN connections ON connections.username1 = 'mikha' AND
                         (connections.username2 = answers.username) 
LEFT JOIN answers answers2 ON (questions.id = answers2.id)
WHERE (answers.id <> answers2.id)

我收到以下错误:

`Unknown connections.username in ON clause`

我在第一次加入时定义了一些条件,并希望得到与这些条件不匹配的其余条件。这就是我使用这部分的原因answers.id AND answers2.id。获取与第一个左连接中的条件不匹配的 ID。

谢谢

4

2 回答 2

1

实际上,如果您通过连接结果限制答案的结果,那么您正在执行内部连接而不是两个左连接,因为一行无法返回而另一行没有结果,因为 null 不等于 null。鉴于这是真的,您可以使用以下内容,因为我不知道您的架构是什么所有架构都是为了保护无辜者而组成的。

SELECT * FROM questions 
left join (
    select connections.otherstuff,answers.id,answers.text from connections 
    inner join answers ON  connections.username2 = answers.username
    where connections.username1 = 'mikha'
 ) conn on questions.id = conn.id

http://sqlfiddle.com/#!2/c7252/1

于 2012-12-09T02:12:44.190 回答
1

像这样尝试,我没有自己测试的架构,但我觉得它应该可以工作(或类似的东西)

SELECT * FROM questions, connections
LEFT JOIN answers ON (questions.id = answers.id AND
                     connections.username2 = answers.username)
where connections.username1 = 'mikha';

最终像这样

SELECT * FROM questions
LEFT JOIN answers ON (questions.id = answers.id)
LEFT JOIN connections ON (connections.username2 = answers.username)
where connections.username1 = 'mikha';

编辑:我在文档中找到了这个

例子:

创建表 t1 (i1 INT); 创建表 t2 (i2 INT); 创建表 t3 (i3 INT); SELECT * FROM t1 加入 t2 ON (i1 = i3) 加入 t3;

以前,SELECT 语句是合法的。现在语句失败,出现 Unknown >column 'i3' in 'on Clause' 错误,因为 i3 是 t3 中的列,它不是 >the ON 子句的操作数。该语句应改写如下:

SELECT * FROM t1 加入 t2 加入 t3 ON (i1 = i3);

所以对于你的情况,它可能是

SELECT * FROM questions  
LEFT JOIN connections
LEFT JOIN answers ON (connections.username1 = 'mikha' AND questions.id = answers.id AND
                 connections.username2 = answers.username)
于 2012-12-09T01:26:19.660 回答