2

我有两个数据库表:

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

4 回答 4

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 小提琴演示

这会给你:

| 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 |
于 2012-12-11T06:42:40.153 回答
0

要按照您的要求显示数据,您还可以在 Excel 中使用诸如数据透视表之类的东西,并将您的数据库作为源。这也适用于 Sql Server Analysis Services。

于 2012-12-11T06:46:40.867 回答
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 
于 2012-12-11T06:50:49.130 回答
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
于 2012-12-11T06:55:54.367 回答