gpt4 book ai didi

php - SQL JOIN 结果不断重复

转载 作者:行者123 更新时间:2023-11-29 02:49:53 24 4
gpt4 key购买 nike

在我的数据库中,我有 3 个表:userphonenumber。他们的结构相应地:

ID | name
---+------
1 | Joe
2 | Gin
3 | Ash


ID | Brand | series
---+-----------+--------
1 | Samsung | s7
2 | Iphone | 6s
3 | Samsung | s5


ID | number
---+----------
1 | 77612
2 | 34014
3 | 98271

我想做的是使用 JOIN 进行选择。这是我的尝试:

$query = "SELECT u.id, p.brand, n.number
FROM `user` u
LEFT OUTER JOIN `phone` p
ON u.id = p.id
LEFT OUTER JOIN `number` n
ON p.id = n.id
WHERE u.id = '$selected'";

$sql = mysql_query($query);

if ($sql === FALSE) {
die(mysql_error());
}

while ($result = mysql_fetch_row($sql)) {
$final[] = $result;
echo '<pre>';
print_r($final);
echo '</pre>';
}

其中 $selected 是表单输入的数组数组,允许选择要显示的 ID,例如:

$selected = array(1, 3);

但结果是:

Array (
[0] => Array (
[0] => 1
[1] => Samsung
[2] => 77612
)
)
Array (
[0] => Array (
[0] => 1
[1] => Samsung
[2] => 77612
)
[1] => Array (
[0] => 3
[1] => Samsung
[2] => 98271
)
)

如果我们设置 $selected = array(1, 2, 3),输出将与上图相同。我该如何解决这个问题?

最佳答案

$selected =  array(array(1), array(2), array(3));

// make list of id from source array
$selected = call_user_func_array('array_merge', $selected);
$selected = implode(',', $selected); // 1,2,3

并将 where 子句更改为

WHERE u.id in ($selected)

关于php - SQL JOIN 结果不断重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37194308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com