Thanks for reading.
I'm trying to learn inner join and join. My aim is to comparing that if the user created the community is also marked as an admin in the CommunityMembers table (I'm not sure if INNER JOIN achieves this) and take all other community information from Community table related to CommunityID (this is possible with inner join as I understand).
I have two tables called Community and CommunityMembers.
the structure is for Community(it has other data such as date, contents etc...):
CommunityID - Slug - CreatedByUser
1 - video - 2
2 - funny - 2
3 - picture - 4
for CommunityMembers
CmID - UserID - Slug - Power
1 - 2 - video - admin
2 - 2 - funny - admin
3 - 4 - picture - admin
my php code: ( $_SESSION['UserID']
is 2 )
<?php
$sql = $dbc->prepare(" SELECT cm.*, com.*
FROM Community com
INNER JOIN CommunityMembers cm ON cm.UserID = com.CreatedByUser
WHERE cm.UserID = '" . $_SESSION['UserID'] . "'");
$sql->execute();
if($sql->rowCount()){
echo $sql->rowCount();
while($data = $sql->fetch()){
$output .= $data['Slug'] .'<br />';
}
echo $output;
}else{
$_ERROR = "no record";
}
?>
echo $output;
prints
video
video
video
funny
funny
funny
and echo $sql->rowcount();
prints 6
Could you please help with this? Why is this printing same thing 3 times? and is my solution right to check if is user created the community is marked as admin in the CommunityMembers or do I need to check it?
Thanks.
Try this
$sql = $dbc->prepare("
SELECT cm.*, com.*
FROM Community com
INNER JOIN CommunityMembers cm ON cm.UserID = com.CreatedByUser
WHERE cm.UserID = '" . $_SESSION['UserID'] . "'
GROUP BY com.CreatedByUser
");
$sql = $dbc->prepare(" SELECT DISTINCT cm.*, com.*
FROM Community com
INNER JOIN CommunityMembers cm ON cm.UserID = com.CreatedByUser
WHERE cm.UserID = '" . $_SESSION['UserID'] . "'");
SELECT DISTINCT
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
If all you need to know if its admin, don't bring all fields from CommunityMembers. Try this
$sql = $dbc->prepare(" SELECT DISTINCT cm.Power, com.*
FROM Community com
LEFT JOIN CommunityMembers cm ON cm.UseriID=com.CreaterByUser
WHERE cm.UserID = '" . $_SESSION['UserID'] . "'");
Didn't test it, but this should work even without DISTINCT.
If you select the 2 tables result SELECT cm.*, com.*
it will return all differents couples so try to select only specifics fields you need.
PS : What is the full result, I mean not only the field slug
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.