2011-06-14 80 views
1

我在这里有一个复杂的MYSQL查询问题。我尽我所能解释我的问题。mysql select multiple and join problem

我有4张桌子。 mid是表格之间的外键。 table4不是必须的表格源。不过,即使没有来自table4的匹配数据,我也喜欢它返回所有行。以便我写下如下的查询脚本。

我不确定是编写这样的查询脚本的逻辑方式,但我知道语法错误。

SELECT * 
FROM table1, table2, table3, 
    (SELECT xx 
    FROM table4 
    RIGHT JOIN table1 ON table1.mid = table4.mid) 
WHERE table1.mid = table2.mid 
AND table1.mid = table3.mid 
AND tt = 'a' 
AND type = 1 
GROUP BY table1.mid 
ORDER BY xx DESC, table1.name ASC; 

在此先感谢

回答

0

你要做的表1 &表4之间的左连接:

SELECT * 
    FROM table1 
    JOIN table2 ON table1.mid = table2.mid 
    JOIN table3 ON table1.mid = table3.mid 
    LEFT JOIN table4 ON table1.mid = table4.mid 
WHERE tt = 'a' 
    AND type = 1 
GROUP BY table1.mid 
ORDER BY xx DESC, table1.name ASC; 
+0

它的工作迷人。感谢高手! :) 但这是唯一的方法? – user610983 2011-06-14 10:02:20

+0

为了您的需要,这是实现它的方式(标准和最简单的方式)。当然,还有其他的方式,比较复杂,但是当你有'LEFT JOIN'时没有兴趣。 – manji 2011-06-14 10:26:06