假设我有一个数据库跟踪我的视频游戏集合。我的目标是检索行并将其转换为以下形式的JavaScript对象:
{
title: "Dark Souls",
releaseYear: 2011,
genres: ["RPG", "Action"],
platforms: ["Windows", "Xbox 360", "PlayStation 3"],
completed: false
}
我想将这些数据存储在SQLite数据库中。我的直觉是像这样组织它。
title : String
releaseYear : Int
completed : Int (0/1 in lieu of boolean type)
name : String
name : String
genres_id : Int
games_id: Int
games_id : Int
platforms_id : Int
我发出了像
这样的查询SELECT games.title,
games.releaseYear,
games.completed,
platforms.name as platforms,
genres.name as genres
FROM games
JOIN games_platforms_link on games_platforms_link.games_id = games.rowid
JOIN platforms on games_platforms_link.platforms_id = platforms.rowid
JOIN games_genres_link on games_genres_link.games_id = games.rowid
JOIN genres on games_genres_link.genres_id = genres.rowid
GROUP BY platforms
希望至少获得" Windows,Xbox 360,PlayStation"作为平台领域,我可以稍后拆分,作为一个起点。但我仍然得到两个单独的行。
我正在阅读我的书籍和网上有关此事,但我想我甚至不太了解甚至搜索的术语,因为我有点挣扎。我真的很感激任何人可以提供的任何提示,甚至让我知道我可以搜索哪些条款以找到相关材料。
答案 0 :(得分:1)
如果您想根据标题,年份和已完成分组平台和流派,请尝试使用以下查询
SELECT games.title,
games.releaseYear,
games.completed,
GROUP_CONCAT(platforms.name) as platforms,
GROUP_CONCAT(genres.name) as genres
FROM games
JOIN games_platforms_link on games_platforms_link.games_id = games.rowid
JOIN platforms on games_platforms_link.platforms_id = platforms.rowid
JOIN games_genres_link on games_genres_link.games_id = games.rowid
JOIN genres on games_genres_link.genres_id = genres.rowid
GROUP BY games.title,games.releaseYear,games.completed
答案 1 :(得分:0)
我认为您可以使用GROUP_CONCAT()函数将platforms
作为逗号分隔列表。
SELECT games.title,
games.releaseYear,
games.completed,
GROUP_CONCAT(platforms.name) as platforms,
GROUP_CONCAT(genres.name) as genres
FROM games
JOIN games_platforms_link on games_platforms_link.games_id = games.rowid
JOIN platforms on games_platforms_link.platforms_id = platforms.rowid
JOIN games_genres_link on games_genres_link.games_id = games.rowid
JOIN genres on games_genres_link.genres_id = genres.rowid
GROUP BY games.title, games.releaseYear, games.completed,
请注意GROUP_CONCAT()
使用逗号作为默认分隔符,因此不需要以逗号形式提供另一个参数。