加入两个表来获取数据

时间:2013-10-25 23:07:34

标签: php mysql join left-join

我想从我的数据库city获取我的位置countrylocation数据。

这是我的代码:

$data = mysql_fetch_array(mysql_query("
SELECT 
u.`prename`,
u.`surname`,
DATE_FORMAT(u.`birthday`, '%d. %M') AS bday,
l.`city`,
l.`country`

FROM 
`users` AS u
LEFT JOIN `users_location` AS ul ON ul.`uid` = u.`id`
LEFT JOIN `locations` AS l ON l.`id` = ul.`location_id`

WHERE u.`id`='".(int) ($_GET['id'])."'"));

users_location中分配了哪个用户具有location_id

users_location结构:iduidlocation_id

locations中有citycountry个名称。

但是,使用我的查询citycountry为空。我猜是因为我的加入声明?

1 个答案:

答案 0 :(得分:2)

我从未使用过“LEFT JOIN table AS t。

简单地“LEFT JOIN table t”,就像这样;

SELECT 
    u.`prename`, u.`surname`, DATE_FORMAT(u.`birthday`, '%d. %M') AS bday, 
    l.`city`, l.`country`
FROM  `users` u
LEFT JOIN  `users_location` ul ON  ul.`uid` = u.`id`
LEFT JOIN  `locations` l  ON  l.`id` = ul.`location_id`
WHERE u.`id` = {$id};

编辑: 请考虑检查数据,而不仅仅是做你做过的事情。

有效的东西;

$id = (array_key_exists('id', $_GET) && is_string($_GET['id']) && ctype_digit($_GET['id']))
    ? $_GET['id'] : FALSE :
if ($id)
{
    SELECT 
        u.`prename`, u.`surname`, DATE_FORMAT(u.`birthday`, '%d. %M') AS bday, 
        l.`city`, l.`country`
    FROM  `users` u
    LEFT JOIN  `users_location` ul ON  ul.`uid` = u.`id`
    LEFT JOIN  `locations` l  ON  l.`id` = ul.`location_id`
    WHERE u.`id` = {$id};
}
else
{
    echo 'No valid ID was provided.';
}