2015-09-13 43 views
-1

我的要求是這樣的:現在到SQL如何加入一個表中的MySQL

select (*ALL columns of table1, [count of rows of TABLE2 where TABLE1.id = Table2.id] 
from TABLE1, TABLE2 
where TABLE1.status = 'A' 

上午,請原諒如果問題太簡單了

+2

(1)您使用的是MySQL還是Oracle?這是兩種不同的產品。 (2)你的問題含糊不清。請顯示樣本數據和期望的結果。 –

+0

[踢壞的習慣:使用舊式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins。 aspx) - 在ANSI - ** 92 ** SQL標準(**超過20年前的**)中,舊式*逗號分隔的表*樣式列表被替換爲* proper * ANSI'JOIN'語法它的使用是不鼓勵的 –

回答

1

使用相關子查詢:

SELECT t1.* 
    ,(SELECT COUNT(*) FROM TABLE2 t2 WHERE t1.id = t2.id) AS Counter 
FROM TABLE1 t1 
WHERE t1.status = 'A'; 
2
select t1.col1, t1.col2, t1.col3, count(t2.id) 
from table1 t1 
left join TABLE2 t2 on t1.id = t2.id 
where t1.status = 'A' 
group by t1.col1, t1.col2, t1.col3