Er图的链接:
我想从子表中获取数据。 例如。我需要所有user_id的位置,设备,语言,服务。给定user_id的位置,设备,语言和服务有多个值。
我尝试了以下代码:
SELECT user_detail.user_id , user_detail.name , user_equipment.equipment , user_location.location , user_service.service , user_language.language
from user_detail
INNER JOIN user_equipment on user_detail.user_id = user_equipment.user_id
INNER JOIN user_location on user_detail.user_id = user_location.user_id
INNER JOIN user_service on user_detail.user_id = user_service.user_id
INNER JOIN user_language on user_detail.user_id = user_language.user_id;
现在的问题是,如果user_id有三个位置我得到三行,有没有办法让所有位置都在同一行?
答案 0 :(得分:0)
您正在寻找这个" GROUP_CONCAT",您的查询将如下所示:
SELECT user_detail.user_id ,
user_detail.name,
GROUP_CONCAT(user_equipment.equipment SEPARATOR ',') as equipments,
GROUP_CONCAT(user_location.location SEPARATOR ',') as locations,
GROUP_CONCAT(user_service.service SEPARATOR ',') as services,
GROUP_CONCAT(user_language.language SEPARATOR ',') as languages
FROM user_detail
INNER JOIN user_equipment on user_detail.user_id = user_equipment.user_id
INNER JOIN user_location on user_detail.user_id = user_location.user_id
INNER JOIN user_service on user_detail.user_id = user_service.user_id
INNER JOIN user_language on user_detail.user_id = user_language.user_id;
GROUP BY user_detail.user_id
答案 1 :(得分:0)
通过按user_id
分组,您可以为每个用户将多行减少为单行。 GROUP_CONCAT
功能可让您查看组中location
的所有值 - 如下所示:
SELECT user_detail.user_id ,
user_detail.name ,
user_equipment.equipment ,
GROUP_CONCAT(user_location.location SEPARATOR ',') AS user_locations ,
user_service.service ,
user_language.language
from user_detail
INNER JOIN user_equipment on user_detail.user_id = user_equipment.user_id
INNER JOIN user_location on user_detail.user_id = user_location.user_id
INNER JOIN user_service on user_detail.user_id = user_service.user_id
INNER JOIN user_language on user_detail.user_id = user_language.user_id
GROUP BY user_detail.user_id;
请注意,这假设每个用户总会有一个(且只有一个)设备,服务和语言记录 - 如果每个用户可以有多个,那么您应该使用GROUP_CONCAT
作为其值( DISTINCT限定符),如果用户可能没有相应的记录,则应将相关表的连接更改为LEFT OUTER JOIN。
答案 2 :(得分:0)
在我无法使用GROUP_CONCAT调用的情况下,我会执行select,然后将它们连接到一些结果代码中。我不确定你使用的是什么应用程序语言,但对于像php这样的东西:
$select = $query(); //Returns the SELECT results
for($i = 0; $i < count($select); $i++){
for($a = 0; $a < count($select); $a++){ //Double loop to check the entire list
if($a !== !i){ //No point in selecting the same row and comparing it
$location_count = 0;
if($select[$a]['user_id'] === $select[$i]['user_id']){
$locationref = 'location_'.$location_count++;
$select[$i][$locationref] = $select[$a]['location'];
}
}
}
}
只是我的想法 - 未经测试,但一般原则就在那里。