来自3个表的MySQL查询(计数)

时间:2011-12-11 20:59:17

标签: mysql

我有3张桌子。

Mark
id_mark
mark_name

example record:
1, 'Ford'
2, 'Fiat'

Model
id_model
id_mark
mondel_name

example record:
1, 1, 'Focus'
2, 2, 'Panda'

Adds
id_adds
id_model
name
price
etc.

example records:
1 1 'My ad', 20000
2 1 'My ad2', 30000
3 2 'My ad3', 30000

如何执行返回结果的查询(Mark Adds Count)示例:

    Ford 2
    Fiat 1

2 and 1 count

3 个答案:

答案 0 :(得分:2)

你需要两个连接。我已将第二个指定为LEFT OUTER JOIN,因此对于没有关联广告的品牌,它可能会返回0。 Mark通过Model加入Adds

SELECT
  mark_name,
  COUNT(id_adds) AS num_ads
FROM
  Mark JOIN Model ON Mark.id_mark = Model.id_mark
  LEFT OUTER JOIN Adds ON Model.id_model = Adds.id_model
GROUP BY mark_name

答案 1 :(得分:2)

SELECT
  mark_name,
  COUNT(id_adds) AS num_adds
FROM  Mark
 LEFT JOIN Model ON Mark.id_mark = Model.id_mark
 LEFT JOIN Adds ON Model.id_model = Adds.id_model
GROUP BY Mark.id_mark

答案 2 :(得分:1)

Select mark.mark_name, count(adds.id_adds) from adds join model on adds.id_model = model.id_model join mark on model.id_mark = mark.id_mark group by mark.id_mark;

我不是100%确定,但这样的事情应该有效