简体   繁体   English

从表一中选择1行,然后从其他表中选择n行,然后返回第一个表并选择第2行,依此类推

[英]Select 1 row from table one and then n number of row from other table and go back to first table and select row 2 and so on

I have this SQL script: 我有这个SQL脚本:

CREATE TABLE `table_1` (
  `IDTable_1` int(11) NOT NULL,
  PRIMARY KEY (`IDTable_1`)
);

CREATE TABLE `table_2` (
  `IDTable_2` int(11) NOT NULL,
  `FK_Table_1` int(11) NOT NULL,
  PRIMARY KEY (`IDTable_2`,`FK_Table_1`),
  KEY `FK_Table_1` (`FK_Table_1`)
);

INSERT INTO `table_1` (`IDTable_1`) VALUES
(1),
(2),
(3);

INSERT INTO `table_2` (`IDTable_2`, `FK_Table_1`) VALUES
(1, 1),
(1, 2),
(2, 1),
(2, 3);

What I want is to create a query to get the data like this: 我想要的是创建一个查询来获取像这样的数据:

1 row from table_1 table_1 1行

n numbers of rows where IDTable_1 appears IDTable_1出现的n行数

Following row from table_1 table_1下一行

n numbers of rows where following IDTable_1 appears 出现以下IDTable_1 n行数

And so on. 等等。

Example of expected result using the data from script provided: 使用提供的脚本中的数据的预期结果示例:

/*ID 1 from table_1*/
1

/*IDs from table_2 Where ID 1 from table_1 appears*/
1
2

/*ID 2 from table_1*/
2

/*IDs from table_2 Where ID 2 from table_1 appears*/
1

/*ID 3 from table_1*/
3

/*IDs from table_2 Where ID 3 from table_1 appears*/
2

But I have no Idea How to achieve this. 但是我不知道如何实现这一目标。 Any ideas would be really appreciated. 任何想法将不胜感激。

We can do this using a union query with a computed column: 我们可以使用带有计算列的联合查询来做到这一点:

SELECT id
FROM
(
    SELECT IDTable_1 AS id, IDTable_1 AS pos1, 1 AS pos2 FROM table_1
    UNION ALL
    SELECT IDTable_2, FK_Table_1, 2 FROM table_2
) t
ORDER BY
    pos1,
    pos2;

Note that a two-level sort is required here. 请注意,此处需要两级排序。 The first level, pos1 , places all records from the same IDTable_1 group together. 第一层pos1将来自同一IDTable_1组的所有记录放在一起。 Then, within each of those groups, the pos2 levels places the record from the first table before the record(s) of the second table. 然后,在每个组中, pos2级别将第一个表中的记录放置在第二个表中的记录之前。

Your question is unclear. 您的问题不清楚。 See which of these work for you: 看看以下哪种方法适合您:

-- close to your output, but formatted differently:
SELECT t2.IDTable_1         AS "Id of table_1",
       GROUP_CONCAT(t2.id)  AS "Ids of table_2"
    FROM table_2
    GROUP BY IDTable_1;

-- Count number of rows:
SELECT IDTable_1, COUNT(*)
    FROM table_2
    GROUP BY IDTable_1;

-- contents of both tables:
SELECT t1.*, t2.*
    FROM table_1 AS t1
    JOIN table_2 AS t2  ON t2.IDTable_1 = t1.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM