[英]MySQL pulling information from multiple table issue
I'm trying to access information from 2 different tables and its retrieving the information but it all so pulling in user information multiple times pending how many fruits listed in table tbl_fruits. 我正在尝试从2个不同的表中访问信息,并试图检索该信息,但是所有这些操作都多次拉入用户信息,以等待表tbl_fruits中列出多少个水果。
like to be able to display user information once and pull what ever number of fruits associated with the user at the same time. 希望能够一次显示用户信息并同时提取与该用户关联的水果数量。
2 tables: tbl_users: userid firstname lastname 2个表:tbl_users:用户标识名姓
tbl_fruits: userid fruit tbl_fruits:用户ID水果
in the example code userID 4 has 3 fruits associated with him in tbl_fruit. 在示例代码中,用户ID 4在tbl_fruit中具有3个与他相关联的水果。 As you can see from the results below the user information is listed multiple times.
从下面的结果中可以看到,用户信息被多次列出。 How can I rewrite the code so that the user information is pulled once and the fruits show up 3 times.
我该如何重写代码,以便将用户信息提取一次,并显示3次结果。
$clientID = "4";
try
{ $stmt = $dbcon1 ->query("SELECT
tbl_fruits.fruit,
tbl_users.userid,
tbl_users.firstname,
tbl_users.lastname
FROM tbl_users
LEFT JOIN tbl_fruits
ON tbl_fruits.userid = tbl_users.userid
WHERE tbl_users.userid = '$clientID' ");
$testArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{ echo $e->getMessage(); }
echo '<pre>';
print_r($testArray);
echo '</pre>';
results 结果
array
(
[0] => Array
(
[fruit] => Apple
[userid] => 4
[firstname] => John
[lastname] => Smith
)
[1] => Array
(
[fruit] => Orange
[userid] => 4
[firstname] => John
[lastname] => Smith
)
[2] => Array
(
[fruit] => Banana
[userid] => 4
[firstname] => John
[lastname] => Smith
)
)
Change your query as below: 如下更改查询:
{ $stmt = $dbcon1 ->query("SELECT
count(tbl_fruits.userid)
tbl_users.userid,
tbl_users.firstname,
tbl_users.lastname
FROM tbl_users
LEFT JOIN tbl_fruits
ON tbl_fruits.userid = tbl_users.userid
WHERE tbl_users.userid = '$clientID'
GROUP BY tbl_users.userid ");
The count(tbl_fruits.userid)
part counts the number of unique rows with that row's value of tbl_fruits.userid
, while the GROUP BY tbl_users.userid
part eliminates the duplicates. count(tbl_fruits.userid)
部分计算具有该行的值tbl_fruits.userid
的唯一行数,而GROUP BY tbl_users.userid
部分则消除重复项。
Be sure to put an index on tbl_users.userid
and tbl_fruits.userid
for best performance. 确保将索引放在
tbl_users.userid
和tbl_fruits.userid
以获得最佳性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.