从具有限制的多个多对多关系表中检索结果

时间:2013-06-10 09:09:32

标签: php mysql many-to-many

表关系图片位于此链接http://www.serofero.net/mvb-table-relation.png

我使用php作为服务器端编程语言,使用MySQL作为数据库。

问题说明

用户添加了新的场地。一个场地可以具有多种饮料,事件,特征等等。现在,我想要这样的查询或魔法,以便我可以收集与每个场地相关的所有饮料,事件,功能,食物,风格,类型,event_options和space_requirements及其venue_id,名称,描述,容量,min_rate,max_rate,位置(来自位置表)。此外,我需要抵消和限制结果,以便我可以在后端实现分页。但挑战是限制应该限制场地的数量,而不是其饮料,食物,风格等。

我也想知道在php数组中收集结果如下:


    $result = array(
    0=> array(
    "name" => "Venue A",
    "description" => "Venue A description",
    "capacity" => "Venue A capacity",
    "location" => "Venue A location",
    "beverages" => array('beverage1','beverage23','beverage7',...),
    "events" => array('event8','event17','event19','event4',...),
    "features" => array('features1',...),
    "foods" => array(),
    "styles" => array(),
    "types" => array('type7', 'type14', 'type23',...),
    "event_options" => array(),
    "space_requirements" => array()
    )
    ,
    1=> array(
    "name" => "Venue B",
    "description" => "Venue B description",
    "capacity" => "Venue B capacity",
    "location" => "Venue B location",
    "beverages" => array('beverage1'),
    "events" => array('event2','event7','event9','event4',...),
    "features" => array(),
    "foods" => array(),
    "styles" => array('style1', 'style2',...),
    "types" => array('type47', 'type4', 'type3',...),
    "event_options" => array(),
    "space_requirements" => array()
    )
    );

今天是第五天我试图找出解决方案,但我一直都失败了。下面是我可以编写的MySQL Query的片段。


    SELECT v.name, e.event, t.type, s.style
    FROM venues v

    LEFT JOIN venue_events ve ON v.venue_id = ve.venue_id
    LEFT JOIN events e ON e.event_id = ve.event_id

    LEFT JOIN venue_types vt ON v.venue_id = vt.venue_id
    LEFT JOIN types t ON t.type_id = vt.type_id

    LEFT JOIN venue_styles vs ON v.venue_id = vs.venue_id
    LEFT JOIN styles s ON s.style_id = vs.style_id

    WHERE v.venue_id IN (SELECT venue_id FROM venues) LIMIT 0,5 
    /* I want to limit the number of "venues" but the LIMIT 0,5 limits the number of   'events', 'types' , 'styles' the "venue" have. And this is the main problem.

    I have also tried :
    WHERE v.venue_id IN (SELECT venue_id FROM venues LIMIT 0,5) but it raises the MySQL error. 
    */

但我不知道接下来要做什么就像上面提到的那样得到结果。

请帮帮我。

三江源。

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT ven.venue_id, ven.name, e.event_id, e.event, t.type_id, t.type, s.style_id, s.style

FROM (SELECT * FROM venues v LIMIT 0,5) ven /*This line does magic for me*/

LEFT JOIN venue_events ve ON ven.venue_id = ve.venue_id
LEFT JOIN events e ON e.event_id = ve.event_id

LEFT JOIN venue_types vt ON ven.venue_id = vt.venue_id
LEFT JOIN types t ON t.type_id = vt.type_id

LEFT JOIN venue_styles vs ON ven.venue_id = vs.venue_id
LEFT JOIN styles s ON s.style_id = vs.style_id