简体   繁体   中英

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:

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

n numbers of rows where IDTable_1 appears

Following row from table_1

n numbers of rows where following IDTable_1 appears

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. Then, within each of those groups, the pos2 levels places the record from the first table before the record(s) of the second table.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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