对于此示例,我们有四个表。
此查询的目标是制定包含单个游戏的计划,然后根据游戏行中的ParentID获取与该游戏相关的所有游戏。
下面的JSON数据详细解释了这一点,我相信
/* GAMES */ {
id: 1,
name: 'Mario Bros',
parent: null
}, {
id: 2,
name: 'Super Mario Bros',
parent: 1
}, {
id: 3,
name: 'Crazy Kong',
parent: 1
}, {
id: 4,
name: 'Mario Sunshine',
parent: 2
}, {
id: 5,
name: 'Dog Fights',
parent: null,
}, {
id: 6,
name: 'War Thunder',
parent: 5
}, {
id: 7,
name: 'Pacman',
parent: null
}
/* SCHEDULE */ {
difficulty: 1,
weekday: 1,
game: 1
}, {
difficulty: 1,
weekday: 1,
game: 5
}, {
difficulty: 2,
weekday: 1,
game: 7
}
在此数据中,时间表由两个游戏(1, 5)
组成,在游戏数据中,ID为(1)
的游戏有三个与parent
相关的游戏:
超级马里奥兄弟和疯狂与数据直接相关,parent
设置为(1)
,Mario Sunshine
与游戏ID (1)
间接相关#39;父母设置为超级马里奥兄弟(2)
另一个ID为(5)
并且难度ID为1
的游戏有一个与之相关的游戏,即War Thunder
,其父级设置为5。
Pacman有2的难度,所以除非你从日程表中搜索难度2,否则它永远不会被提起,然后其他6场比赛将永远不会出现。
我需要一个查询,可以根据日程表中的基本条目查找所有相关游戏,该查询由难度ID检索。
由以下查询返回的游戏:
SELECT ALL RELATED GAMES FROM SCHEDULE WHERE DIFFICULTY = 1
应该是:
这是一个SQLFiddle:http://sqlfiddle.com/#!9/f7583/5
目标是根据表中所有行的父ID,以递归方式查找原始id的所有条目。
关系:
'Mario Bros': [
'Super Mario bros': [ 'Mario Sunshine' ],
'Crazy Kong': [],
],
'Dog Fights': [
'War Thunder'
]
答案 0 :(得分:0)
一种可能性
SELECT schedules.*, games.name
FROM schedules
INNER JOIN games ON games.id = schedules.gameId or games.parentId = schedules.gameId
WHERE schedules.weekday = 1
AND difficultyId = 1;
这是一个有效的演示http://sqlfiddle.com/#!9/f7583/57
答案 1 :(得分:0)
最多3个级别:
CREATE TEMPORARY TABLE temp_sc (
id INT NOT NULL,
gameId INT,
name VARCHAR(255),
difficultyId INT,
weekday INT,
variation TINYINT(1) default false,
deviceId INT NOT NULL,
parentId INT DEFAULT NULL
);
INSERT INTO temp_sc (id, gameId, name, difficultyId, weekday, deviceId, parentId)
SELECT distinct sc.id, g3.id, g3.name, sc.difficultyId, sc.weekday, g3.deviceId, g3.parentId
FROM schedules as sc
LEFT JOIN games as g1 ON g1.id = sc.gameId
LEFT JOIN games as g2 ON g2.parentid = g1.id || g2.id=g1.id
LEFT JOIN games as g3 ON g3.parentid = g2.id || g3.id=g2.id
WHERE sc.weekday = 1
AND sc.difficultyId = 1;
SELECT temp_sc.name as 'Game Name', temp_sc.gameId as 'Game ID', temp_sc.parentId as 'References ID', dev.name as 'Device' FROM temp_sc
LEFT JOIN devices as dev ON temp_sc.gameID = dev.id;