给出有关对象的信息:id,user_id,group_id
给出关于用户的信息:id_user,id_loc
我需要得到一个查询:
用户名(在表用户中)
用户所在地的名称(在表格中)
对象组的名称(在表组中)
我这样想:
SELECT usuarios.first_name as username
, usuarios.id as userid
, usuarios.avatar as useravatar
, usuarios.id_loc
, locs.name as locname
, groups.name as groupname
FROM usuarios,groups,locs
WHRE usuarios.id_loc = locs.id
AND usuarios.id = 1
AND group.id = LIMIT 1
说错误
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 在第3行'AND locs.id = 3 LIMIT 1'附近
我做错了什么?我可以在一个查询中执行此操作吗?
- 编辑 -
这是查询生成器代码(php + mysql):
$query_loc_group_user = 'SELECT usuarios.first_name as username,
usuarios.id as userid,
usuarios.avatar as useravatar,
usuarios.id_loc,
locs.name as locname,
groups.name as groupname
FROM usuarios,groups,locs
WHRE usuarios.id_loc = locs.id
AND usuarios.id = '.$this->id_user.'
AND group.id = '.$this->id_group.'
LIMIT 1';
如果有帮助,我试图在一个查询中执行此操作
function get_info(){
$info;
$result = cache_query('SELECT first_name,last_name,avatar FROM usuarios WHERE id = '.$this->id_user);
foreach($result as $extra){
$info['username'] = $extra['first_name'].' '.$extra['last_name'];
$info['avatar'] = $extra['avatar'];
}
$result1 = cache_query('SELECT name FROM locs WHERE id = '.$this->id_user);
foreach($result1 as $extra){
$info['locname'] = $extra['name'];
}
$result2 = cache_query('SELECT name FROM groups WHERE id = '.$this->id; /*objectid*/
foreach($result2 as $extra){
$info['groupname'] = $extra['name'];
}
return $info;
}
答案 0 :(得分:0)
这个怎么样?
$sql = 'SELECT usuarios.name as username,usuarios.avatar as useravatar, usuarios.id_loc, locs.name as locname';
$sql .= ' FROM usuarios, groups, locs';
$sql .= ' WHERE usuarios.id = '.$this->id_user.' AND groups.id = '.$this->id_group.' AND locs.id = '.$this->id_loc.' LIMIT 1';
$res = mysql_query($sql) or die(mysql_error());
答案 1 :(得分:0)
您需要将某些事物或地方与群体联系起来。我不知道你的架构,但它可能是这样的:
SELECT
usuarios.first_name as username,
usuarios.id as userid,
usuarios.avatar as useravatar,
usuarios.id_loc,
locs.name as locname,
groups.name as groupname
FROM
usuarios,
groups,
locs
WHRE
usuarios.id_loc = locs.id AND
[something?] = groups.id AND -- This is what you're missing.
-- What table/column relates to groups?
usuarios.id = 1 AND
group.id = 1
LIMIT 1
...其中[something?]可能是usuarios或locs中的id_group列。现在,您的热门查询有两个错误。第一个是简单的语法错误,您没有指定group.id值。但是,第二个更严重的是,您的组表没有连接子句。
如果你发布了三张桌子的模式,我可能会给你一个更好的答案,但我打赌这是你所缺少的。如果您在usuarios或locs中没有group_id列,那么您需要更清楚地了解您要查询的内容,并且某些示例数据可能对您的预期结果有所帮助。
答案 2 :(得分:0)
SELECT usuarios.first_name,usuarios.last_name,usuarios.avatar,poblacion.poblacion,groups.name as groupname
FROM usuarios LEFT JOIN poblacion ON usuarios.id_loc=poblacion.idpoblacion,
helps LEFT JOIN groups ON helps.id_group = groups.id
WHERE usuarios.id = '.$this->id_user.' AND groups.id = '.$this->id_group