如何只使用一个SELECT进行此SQL查询

时间:2014-03-05 16:29:50

标签: mysql sql union

我在创建一个特定的SQL查询时遇到了麻烦,只在一个查询中(我不能去数据库两次,对于设计架构,请相信我)这里是语句:

我有四张桌子: 问题, 位置, 国家, 区域

这是他们的一些领域:

Questions
    id
    description
Locations
    id
    type (could be 'country' or 'region')
    question_id
    country_or_region_id (an id, that holds either the country or the region id)
Countries
    id
    name
Regions
    id
    name

我想得到的是:

示例:

1       What is your name?        Venezuela, Colombia              South America

格式:

question id,      question description,       countries,        regions

编辑:对于那些问我的人,我正在使用MySQL

编辑:对于那些说它设计不好的人:我没有创建它,我无法改变设计,我只需要这样做,就像现在一样。

3 个答案:

答案 0 :(得分:0)

删除Locations表并将question_id添加到Regions和Countries表

select Q.id, Q.description, C.name as country, R.name as region 
from Questions as Q join Countries as C join Regions as R 
where Q.id = L.question_id and Q.id = C.question_id and Q.id = R.question_id;

答案 1 :(得分:0)

如果是MySQL:

SELECT  q.ID,
        q.Description,
        GROUP_CONCAT(DISTINCT c.name) AS countries,
        GROUP_CONCAT(DISTINCT r.name) AS regions
FROM    Questions q
        INNER JOIN Locations l
            ON l.question_id = q.id
        LEFT JOIN Countries c
            ON c.id = country_or_region_id
            AND l.type = 'country'
        LEFT JOIN Regions R
            ON R.id = country_or_region_id
            AND l.type = 'region'
GROUP BY q.ID, q.Description;

如果这是SQL-Server:

SELECT  q.ID,
        q.Description,
        countries = STUFF(( SELECT ', ' + c.name
                            FROM    Locations l
                                    INNER JOIN Countries c
                                        ON c.id = country_or_region_id
                                        AND l.type = 'country'
                            WHERE   l.question_id = q.id
                            FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)'), 1, 2, ''),
        regions = STUFF((   SELECT ', ' + r.name
                            FROM    Locations l
                                    INNER JOIN Regions r
                                        ON r.id = country_or_region_id
                                        AND l.type = 'region'
                            WHERE   l.question_id = q.id
                            FOR XML PATH(''), TYPE
                        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
FROM    Questions q;

答案 2 :(得分:0)

SELECT questions.id
     , questions.description
     , Group_Concat(countries.name) As countries
     , Group_Concat(regions.name) As regions
FROM   questions
 INNER
  JOIN locations
    ON locations.question_id = questions.id
 LEFT
  JOIN countries
    ON countries.id = locations.country_or_region_id
   AND locations.type = 'country'
 LEFT
  JOIN regions
    ON regions.id = locations.country_or_region_id
   AND locations.type = 'region'
GROUP
    BY questions.id
     , questions.description