我有这个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);
我想要创建一个查询以获取像这样的数据:
table_1
中的1行
n个出现IDTable_1
的行数
以下是table_1
的行
n个出现在IDTable_1
之后的行数
以此类推。
使用提供的脚本中的数据得出的预期结果示例:
/*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
但是我不知道如何实现这一目标。任何想法都将不胜感激。
答案 0 :(得分:1)
我们可以使用带有计算列的联合查询来做到这一点:
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;
请注意,此处需要两级排序。第一级pos1
将来自同一IDTable_1
组的所有记录放在一起。然后,在每个组中,pos2
级别将第一个表中的记录放在第二个表中的记录之前。
答案 1 :(得分:0)
您的问题尚不清楚。看看其中哪些适合您:
-- 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;