Mysql Group_concat然后根据结果查询

时间:2012-09-29 15:00:55

标签: mysql

大家好,我有一个表业务,有很多很多关系。有人建议我首先执行一个组concat以从许多表中获取想法,然后查看这些id以从多个表中获取值

在下面的例子中,我可以看到我通过GROUP_CONCAT(DISTINCT ba.announcement_id)获取公告ID列表作为'公告',如何从这里设置

来自公告的SELECT *     其中id IN( _ __ _ __ _

其中in表示从group_concat返回的内容

id b

BEGIN

/* Business Information and Categories */
SELECT 
    b.alias_title, b.title, b.premisis_name, 
    a.address_line_1, a.address_line_2, a.postal_code,tvc.town_village_city,spc.state_province_county, c.country,
    GROUP_CONCAT(DISTINCT be.event_id) as 'event',
    GROUP_CONCAT(DISTINCT ba.announcement_id) as 'announcement', 
    GROUP_CONCAT(DISTINCT bd.document_id) as 'document',
    GROUP_CONCAT(DISTINCT bi.image_id) as 'image',
    GROUP_CONCAT(DISTINCT bprod.product_id ) as 'product',
    GROUP_CONCAT(DISTINCT bt.tag_title_id) as 'tag'
    FROM business AS b
    INNER JOIN business_category bc_1 ON b.primary_category = bc_1.id
    INNER JOIN business_category bc_2 ON b.secondary_category = bc_2.id
    LEFT OUTER JOIN business_category bc_3 ON b.tertiary_category = bc_3.id
    INNER JOIN address a ON b.address_id = a.id
    LEFT OUTER JOIN town_village_city tvc ON a.town_village_city_id = tvc.id
    LEFT OUTER JOIN state_province_county spc ON a.state_province_county_id
    INNER JOIN country c ON a.country_id = c.id
    LEFT OUTER JOIN geolocation g ON b.geolocation_id = g.id
    LEFT OUTER JOIN business_event be ON b.id = be.event_id
    LEFT OUTER JOIN business_announcement ba ON b.id = ba.announcement_id
    LEFT OUTER JOIN business_document bd ON b.id = bd.business_id
    LEFT OUTER JOIN business_image bi ON b.id = bi.business_id
    LEFT JOIN business_property bp ON b.id= bp.business_id
    LEFT JOIN business_product bprod ON b.id= bprod.business_id 
    LEFT JOIN business_tag bt ON b.id = bt.business_id
    WHERE b.id= in_business_id;

    SELECT * from announcement 
    where 




END

1 个答案:

答案 0 :(得分:0)

在您的第一个选择语句中,您可以将announcementId分配给变量,然后使用它来获取第二个查询中的所有公告:

set @announcementIds = '';
select ...........,
@announcementIds:= GROUP_CONCAT(DISTINCT announcement_id) as 'announcement',
...........;

Select * from announcement 
where announcement_id REGEXP REPLACE(@announcementIds,',','|');

一些链接: