来自两个表的匹配行并将它们显示为新行

时间:2016-07-28 09:38:27

标签: mysql sql

假设我在表格中的数据说表1 如下:

QuesID QuesName       
     1 Question 1
     2 Question 2
     3 Question 3
     4 Question 4

表2 中,如下所示:

ID QuesID MainQuesID
 1      4          1
 2      2          2 

我希望得到以下输出:

QuesID QuesName       
     1 Question 1
     1 Question 4
     2 Question 2
     2 Question 2
     3 Question 3
     4 Question 4

实际上是否可以使用Sql?我尝试了以下内容,但即使它与ID不匹配也会返回所有问题(按主要问题顺序排序):

SELECT m.QuesID
     , m.QuesName
  FROM Table_1 m 
 GROUP 
    BY m.QuesID
     ,m.QuesName
 UNION ALL 
SELECT k.QuesID
     , m.QuesName
  FROM Table_2 k

3 个答案:

答案 0 :(得分:1)

我假设,根据您发布的结果,mapStateToProps的条目将由Table_2列出。

MainQuesID

Table_2与Table_1连接,以获取每个qstnID的问题标题。

然后将两个表放入格式(SELECT * from ((SELECT t1.QuesID, t1.QuesName FROM Table_1 t1) UNION (SELECT t2.MainQuesID as QuesID, t1.Title as QuesName FROM Table_2 t2 JOIN Table_1 t1 ON t1.QuesID = t2.QuesID)) as union_table ORDER BY union_table.QuesID QuesID),然后将它们联合起来,然后通过QuesID对它们进行排序。

答案 1 :(得分:0)

这是您需要的结果:

select QuesID,Quesname from
(select QuesID,Quesname from table_1

union all

select id,QuesName from Table_2) as a order by QuesID 

enter image description here

与您想要的结果相同

答案 2 :(得分:-1)

尝试以下代码


CREATE TABLE #table1 (
    QuesID INT
    ,QuesName VARCHAR(100)
    )
INSERT INTO #table1
VALUES (
    1
    ,'Question 1'
    )
INSERT INTO #table1
VALUES (
    2
    ,'Question 2'
    )
INSERT INTO #table1
VALUES (
    3
    ,'Question 3'
    )
INSERT INTO #table1
VALUES (
    4
    ,'Question 4'
    )

CREATE TABLE #table2 (
    ID INT
    ,QuesID INT
    ,QuesName VARCHAR(100)
    ,MainQuesID INT
    )
INSERT INTO #table2
VALUES (
    1
    ,4
    ,'Question 4'
    ,1
    )
INSERT INTO #table2
VALUES (
    2
    ,2
    ,'Question 2'
    ,2
    )

SELECT *
FROM (
    SELECT QuesID
        ,QuesName
    FROM #table1

    UNION ALL

    SELECT MainQuesID
        ,QuesName
    FROM #table2
    ) A
ORDER BY QuesID