MySQL将LIMIT设置为' child' JOIN操作表

时间:2016-05-05 14:13:38

标签: mysql

我有两个具有多对多关系的mysql表

驱动程序

id           name         ...

1            'joe'
2            'bill'
3            'john'
...

总线

id           name         ...

1            'school'
2            'student'
3            'worker'
...

drivers_buses

id           driver_id_inner   bus_id_inner

1            1                 1
2            2                 1
3            2                 2
4            2                 3
5            1                 3
...

如何选择总计数驱动程序小于3的驱动程序。即如果驱动程序有5个总线,则只显示前3个总线。

我试着通过一些JOIN操作来获取它,但它会使公交车的计数少于三个。

        SELECT DRIVER.*, DRIVER_BUSES.bus_id_inner FROM drivers AS DRIVER

        INNER JOIN drivers_buses AS DRIVER_BUSES ON DRIVER.driver_id = DRIVER_BUSES.driver_id_inner

        INNER JOIN
          (
             SELECT drivers_buses.driver_id_inner
                    FROM drivers_buses GROUP BY drivers_buses.driver_id_inner HAVING COUNT(drivers_buses.driver_id_inner)<= 3
          )
        AS lessthenthree
        ON DRIVER.driver_id = lessthenthree.driver_id_inner

2 个答案:

答案 0 :(得分:1)

select d.*, db.bus_id
from drivers d
join (
    select db1.driver_id, db1.bus_id
    from drivers_buses db1
    join drivers_buses db2 
        on  db1.driver_id = db2.driver_id
        and db2.id <= db1.id
    group by db1.driver_id, db1.bus_id
    having count(db2.id) <= 3
) db on db.driver_id = d.id

http://sqlfiddle.com/#!9/2a4d26/3

如果超过三辆,您需要决定显示哪三辆巴士。在这个解决方案中,我按照drivers_buses.id排序前三个。

答案 1 :(得分:0)

您不必担心在Mysql查询端限制给定驱动程序的总线数量。您始终可以在前端perspect上隐藏不需要的数据。你不需要做这么复杂的查询。

做这样的事情:

select count(*), D.name,B.name 
from drivers D, buses B, drivers_buses DB 
where GROUP BY D.name

如果你让编程语言处理这样的任务,这很好,因为你在那里有很大的灵活性。

请在前端更新您的问题,了解您如何显示数据,无论是php还是其他任何语言。