2014-03-05 44 views
0

我只能在一個查詢中創建特定的SQL查詢時遇到問題(我不能兩次訪問數據庫,對於設計體系結構,請相信我)這裏的語句:如何使這個SQL查詢只有一個SELECT

我有四個表: 問題, 位置, 國家, 地區

這是他們的一些領域:

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 

編輯:對於那些誰問,我m使用MySQL

編輯:對於那些說這是一個糟糕的設計:我沒有創造它,我不能改變設計,我只需要這樣做,就像現在這樣。

+4

你到目前爲止嘗試過什麼?你遇到什麼問題?你能提供樣本數據/期望的輸出嗎? –

+1

您如何期望系統知道'Locations'表中的country_or_region_id是國家還是地區ID? – hanleyhansen

+0

@hanleyhansen這是類型字段的用途。但是你沒有從國家到地區的鏈接。 – theB3RV

回答

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-服務器:

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; 
+0

這是爲MySQl,我要檢查你的代碼,並讓你知道。 –

+0

嗯,這就是我所需要的** GROUP_CONCAT **功能!雖然,我的解決方案略有不同。 –

0

取出位置表並添加question_id到區域和國家表

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; 
+0

我不能刪除一個表,它是一個已經工作的系統,不能觸摸它:( –

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 
+0

你爲什麼沒有'GROUP BY'? –

+0

@FranciscoCorrales我懶洋洋地用'DISTINCT'代替。 – gvee

+0

會使用DISTINCT的成本更高嗎?,我認爲效率不高。 –

相關問題