我需要创建一个mysql查询,该查询应该从两个表中仅获取一行结果。
我有一个名为users的表和一个名为users_sports的表。
let context = appdelegate.persistentContainer.viewContext
let proj = Project()
let arrProj = dic.object(forKey: "Projects") as! NSArray
for n in 0..<arrProj.count {
let subDic = arrProj.object(at: n) as! NSDictionary
let item = ProjectItem(dict: subDic)
proj.arrProjs.append( item )
let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
projects?.setValue(item.Project, forKey: "project1")
projects?.setValue(item.Project2, forKey: "project2")
projects?.setValue(item.ID, forKey: "projectid")
projects?.setValue(item.radius, forKey: "radius")
projects?.setValue(item.GeofenceType, forKey: "geo_Type")
projects?.setValue(item.Geofence, forKey: "geofence")
projects?.setValue(item.Coordinates, forKey: "coordinates")
}
我只需要一行中包含表用户的所有用户值和特定用户的所有user_sport_sport值的查询结果。
例如:SELECT * FROM users WHERE id = 71
SELECT user_sport_sport FROM users.sports WHERE user_sport_user = 71
编辑tb_user_sports
表格用户
表tb_sports
答案 0 :(得分:2)
您可以使用group_concat来获取该用户ID的所有体育项目
select u.name, GROUP_CONCAT(ts.sport_name) sports from users u
join tb_user_sports tus ON tus.user_sport_user = u.id
left join tb_sports ts ON ts.id_sport = tus.user_sport_sport
where u.id = 72
group by u.id
来源:https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat