查询将问题与来自两个不同表格的选项相结合?

时间:2012-12-11 06:34:57

标签: sql sql-server

我有两个数据库表:

Definitions表包含以下列:

Id, Category

示例数据:

1, What is capital of USA ?
2, Who broke my glass ?

Options表包含以下列:

Id, DefinitionId, Value

示例数据:

1, 1, New York
2, 1, Melbourne
3, 1, Lahore
4, 2, Boss
5, 2, My brother
6, 2, Your girlfriend

请指导我如何使用所有选项查询所有问题,我需要以下数据:

"", 1, What is capital of USA ?
1,1, New York
2,1, Melbourne
3, 1, Lahore

"", 2,Who broke my glass ?
4, 2, Boss
5, 2, My brother
6, 2, Your girlfriend

请指导

4 个答案:

答案 0 :(得分:1)

为此,请使用UNION ALL,如下所示:

SELECT '' ID, DefinitionId, Category AS value FROM Definitions WHERE ID = 1
UNION ALL
SELECT Id, DefinitionId, Value FROM Options WEHRE DefentionID = 1;

请注意:最好JOIN这两个表如下:

SELECT 
  d.Id,
  o.Id,
  o.Value
FROM Definitions d
INNER JOIN Options o ON d.ID = o.DefinitionId
WHERE d.Id = 1;

不要考虑在SQL中进行这种格式化;

更新:要获得所有问题,请尝试以下操作:

SELECT '' ID, ID AS DefinitionId, Category AS value FROM Definitions 
UNION ALL
SELECT Id, DefinitionId, Value FROM Options
ORDER BY DEFINITIONID, ID;

SQL Fiddle Demo

这会给你:

| ID | DEFINITIONID |                    VALUE |
------------------------------------------------
|  0 |            1 | What is capital of USA ? |
|  1 |            1 |                 New York |
|  2 |            1 |                Melbourne |
|  3 |            1 |                   Lahore |
|  0 |            2 |     Who broke my glass ? |
|  4 |            2 |                     Boss |
|  5 |            2 |               My brother |
|  6 |            2 |          Your girlfriend |

答案 1 :(得分:0)

要像您要求的那样显示您的数据,您还可以使用Excel中的数据透视表和数据库作为源。这也适用于Sql Server Analysis Services。

答案 2 :(得分:0)

SELECT ' ',D.ID,D.category from Definitions D where D.Id = 1
UNION 
SELECT C.ID,C.DefinitionId,C.Value from options C where C.DefinitionId=1 

答案 3 :(得分:0)

SELECT  NULL,D.Id,D.Category
FROM    Definitions D
UNION
SELECT  O.Id,O.DefinitionId,O.Value
FROM    Options O
ORDER BY 2,1