在JOINED

时间:2017-12-25 02:15:35

标签: php mysql mysqli prepared-statement

我只是想知道,如何检索表中不存在的行并将其返回为NULL?

简要

例如,在下面的代码中,它只返回skill_players中存在的数据,这不是我想要的结果。我想要的结果是,输出现有数据以使其值来自 skill_players 如果不存在然后将值输出为 NULL 以便我可以使用 IFNULL 用于以后目的。

表格设计

skills_type

skill_players

当前结果

[Skill Name]        | [Value]
TotalStoreRobbed    |  8

预期结果

[Skill Name]        | [Value]
TotalRape           |  NULL
TotalBeenRaped      |  NULL
TotalRob            |  NULL
TotalBeenRobbed     |  NULL
TotalStoreRobbed    |  8
TotalCuffEscape     |  NULL
TotalArrest         |  NULL
TotalBeenArrested   |  NULL

代码

//fetching item data
$query =
"
    SELECT
        skill.value, type.skill_name
    FROM
        skills_player AS skill
    LEFT JOIN
        skills_type AS type
    ON
        skill.fk_skill_id = type.skill_id
    WHERE
        skill.fk_user_id = ?
";
if($stmt = $sqlHandle->prepare($query))
{
    $stmt->bind_param("i", $acc_ID);
    $stmt->execute();
    $res = $stmt->get_result();

    $skills = null;
    if($res->num_rows > 0) {
        while($row = $res->fetch_assoc()) {
            $skills[] = $row;
            print_r($row);
        }
    }
}
else {
    $error = $sqlHandle->errno . ' ' . $sqlHandle->error;
    echo $error;
}

谢谢,帕特里克!

1 个答案:

答案 0 :(得分:0)

WHERE子句移动到ON子句,并更改连接的顺序。向玩家留下加入技能,从而保留所有技能。

SELECT
    skill.value, type.skill_name
FROM
    skills_type AS type
LEFT JOIN
    skills_player AS skill
ON
    skill.fk_skill_id = type.skill_id AND
    skill.fk_user_id = ?

当前查询的问题在于,虽然它确实使用LEFT JOIN,但它会丢弃skills_player表中给定用户没有的任何记录。相反,您想要显示每个技能记录,无论用户是否具有该技能。