Creating a group of users in PHP and MySQL - php

I'm wondering how I can use JOIN or LEFT JOIN to group users.
users table:
id (primary)
user (varchar)
pass (varchar)
email (varchar)
website (varchar)
bio (text)
avatar (varchar)
code (varchar)
active (varchar)
admin (varchar)
group_1 (int) <--- I have a feeling that this is the wrong way to go about it
group_2 (int) <---
group_3 (int) <---
groups table:
group_id (primary key)
group_name (varchar)
group_bio (text)
group_website (varchar)
I was wondering how I could let a member be part of several groups and to show a list of members of a certain group..
Something like this:
Group Name
Users: <a href='profile'>Name</a>, <a href='profile'>Name</a>, <a href='profile'>Name</a>, <a href='profile'>Name</a>
I have absolutely no idea how to go about this. Please help.

You want a standard many-to-many relationship.
This is usually implemented by having three tables.
Users
Groups
Memberships
The memberships table will have two foreign keys, which map on to the other two tables.

You have to create a new table MEMBER_GROUPS with two fields: user_id and group_id.
Every row is a membership of a user...
In this way you can easily query user membership in a group...

This is indeed the wrong approach, as it restricts a user to three group memberships. This is a classic many-to-many relationship, and you can model it using a bridge table:
user_group
----------
user_id
group_id
The primary key will be a composite of user_id and group_id, enforcing uniqueness. Then you would do a double-join through this table. For example, to get all of the members of all of the groups:
SELECT group.*, user.*
FROM group
LEFT OUTER JOIN user_group
ON group.group_id = user_group.group_id
LEFT OUTER JOIN user
ON user_group.user_id = user.user_id
Or, if you are after a specific group:
SELECT user.*
FROM user_group
INNER JOIN user
ON user_group.user_id = user.user_id
WHERE user_group.group_id = ?
You could even get a list of all groups, with membership count:
SELECT group.*, COUNT(user_group.user_id) AS group_membership_count
FROM group
LEFT OUTER JOIN user_group
ON user_group.group_id = group.group_id
GROUP BY group.group_id

Related

Fetch data from a single table with some conditions?

I am making a skill sharing website for a project.Tables in database are as follows:
users(id,name,email,password)
skills(id,skillname)
haveskills(id,user_id,skill_id)
{user_id references id in users and skill_id references id in skills}
wantskills(id,user_id,skill_id)
{user_id references id in users and skill_id references id in skills}
friends(id,user_id1,user_id2)
{say user with id 1 and 3 are friends then I have two rows first:user_id1=1,user_id2=3;second:user_id1=3,user_id2=1}
When a user is logged in I have these infos:His
id,haveskill_id(hid),wantskill_id(wid).
I want sql query for all the users id whose
haveskill_id=wid,wantskill_id=wid and are NOT friends.
Edit:My query which fulfills first two conditions but I am having problem with third condition:
SELECT A.id FROM users A JOIN haveskills B
ON (A.id=B.user_id And B.skill_id='$wantskill_id')
JOIN wantskills C
ON (A.id=C.user_id AND C.skill_id='$haveskill_id');

Outputting all data in a table and showing which rows belong to a user

I have a roles table which contains various user roles.
A pivot tables joins this to my users table.
users
id | name
roles
id | title
user_role
user_id | role_id
I would like to display all roles that exist and pre tick the ones that belong to a specific user.
How would I go about this, I take it I cannot do this in mySQL?
I was considering getting all roles with one query, then with another query get all roles that belong to a specific user.
Then loop through all roles and if there is a match with the specific users roles, output a checked box instead of an unchecked one.
Is there a better way?
Something like
SELECT R.id as role_id,
R.title as role_title,
UR.user_id as user_id,
U.name as user_name
FROM Roles R
LEFT JOIN user_role UR
ON UR.role_id = R.id
AND UR.user_id = :myuserid
LEFT JOIN users U
ON U.id = UR.user_id
should return a complete list of roles, with either a NULL or the user id in the user column to indicate any roles that the user has been granted (user identified by id as :myuserid)
I think normal SQL Query can do most of the work: Checkout this SQLFIddle for sample of what your query might look like
SELECT r.* FROM roles r LEFT JOIN user_role ur ON r.id=ur.role_id WHERE ur.user_id=3;

Joining 2 Tables and show the same column repeatedly based on its associative ID

Hi i am not sure how to put this in a brief sentences, but i have DB table like the following
User Table
user_id
username
and so on...
Item
item_id
item_name
Item_Equipped
equipped_id head (FK to item_id)
hand (FK to item_id)
user_id (FK to user_id IN User Table)
I would like to generate a query that will display like the following format
user_id | head | head_item_name | hand | hand_item_name | ...
So far i only able to do this:
SELECT user.user_id, user.username,
equipments.head, equipments.head_acc,
equipments.hand,
equipments.acc, equipments.body
FROM gw_member_equipped AS equipments
LEFT JOIN gw_member AS user ON user.memberid = equipments.member_id
Which (i have to be brutally honest) doesn't do anything much.
I tried to perform INNER JOIN between item and item_equipped however i am unable to get individual name for each item (based on its item ID)
you need to join ITEM table two times with ITEM_EQUIPPED table.
you can use below query for your desired output column shown in question..
SELECT USER.User_Id,
Item_Equipped.Head,
Item_Heads.Item_Id Head_Item_Id, -- if you want you can remove this column
Item_Heads.Item_Name Head_Item_Name,
Item_Equipped.Hand,
Item_Hands.Item_Id Hand_Item_Id, -- and this column also as these columns are same as their previous select columns
Item_Hands.Item_Name Hand_Item_Name
FROM USER, Item Item_Heads, Item Item_Hands, Item_Equipped
WHERE USER.User_Id = Item_Equipped.User_Id
AND Item_Heads.Item_Id = Item_Equipped.Head
AND Item_Hands.Item_Id = Item_Equipped.Hand

filtering sql search by two variables having same result

I'm not sure how I can do this but I have two tables:
--users--
id_users (index)
name_users
--friend--
id_friend (index)
id_user (connects to id_users)
linked_friend (also links to id_users as this is the id of the requested friend)
for a friendship to be requested one row exists with the user who requested in friend.id_user col and the user they are requesting being in the friend.linked_friend col. To confirm the friendship link another row is created with the info reversed so that there are two rows for each friendship with each user being in the friend.id_user AND the friend.linked_friend col. (let me know if I could do this in a better way)
so what I need to do is for each user list all users on the system that are in a confirmed friendship (two rows) and aren't themselves.
SELECT id_user, name_user FROM user WHERE id_user <> $userId
obviously removes themselves from the list but I'm at a loss as to how to select users that have both rows.
I hope that is clear enough.
Thanks
You could join the friend table twice to demand that rows in both direction exist:
select u1.name
, u2.name
from users u1
join friend f1
on u1.id_users = f1.id_user
join friend f2
on f2.id_user = f1.linked_friend
and f2.linked_friend = f1.id_user
join users u2
on u2.is_users = f2.id_user
and u1.id_users < u2.id_users -- Display friends once
I agree with Jack Pettinger that this design is fairly clunky. There should be only one row in the friends table for each relation. It should have a unique constraint to enforce that, like:
alter table Friends add constraint CHK_Friend check (friend1_id < friend2_id);
create index UX_Friends on Friends (friend1_id, friend2_id);
you have to use Join if you want to fetch data from two or more tables.
Try this
select * from users left join friend on users.id_users = friend.id_user
// you also give where condition for particular user_id

MySQL: Understanding mapping tables

When building a category navigation system for a business directory with a many to many relationship, I understand that it is good practise to create a mapping table.
Category Table ( CategoryId, CategoryName )
Business Table ( BusinessId, BusinessName )
Category Mapping Table ( BusinessId, CategoryId )
When I join the Category table and Business table to create the mapping table would this then give me a table which contains every possible business and category relationship?
I have 800 categories and 1000 business listings. Would that then give me a table containing 800,000 possible relationships. If so how would I focus on only the relationships that exist? Would I have to go through all listings (800,000) marking them as true or false?
I have been getting really confused about this so any help would be much appreciated.
When using many-to-many relationships, the only realistic way to handle this is with a mapping table.
Lets say we have a school with teachers and students, a student can have multiple teachers and visa versa.
So we make 3 tables
student
id unsigned integer auto_increment primary key
name varchar
teacher
id unsigned integer auto_increment primary key
name varchar
link_st
student_id integer not null
teacher_id integer not null
primary key (student_id, teacher_id)
The student table will have 1000 records
The teacher table will have 20 records
The link_st table will have as many records as there are links (NOT 20x1000, but only for the actual links).
Selection
You select e.g. students per teacher using:
SELECT s.name, t.name
FROM student
INNER JOIN link_st l ON (l.student_id = s.id) <--- first link student to the link-table
INNER JOIN teacher t ON (l.teacher_id = t.id) <--- then link teacher to the link table.
ORDER BY t.id, s.id
Normally you should always use an inner join here.
Making a link
When you assign a teacher to a student (or visa versa, that's the same).
You only need to do:
INSERT INTO link_st (student_id, teacher_id)
SELECT s.id, t.id
FROM student s
INNER JOIN teacher t ON (t.name = 'Jones')
WHERE s.name = 'kiddo'
This is a bit of a misuse of an inner join, but it works as long as the names are unique.
If you know the id's, you can just insert those directly of course.
If the names are not unique this will be a fail and should not be used.
How to avoid duplicate links
It's very important to avoid duplicate links, all sorts of bad things will happen if you have those.
If you want to prevent inserting duplicate links to your link table, you can declare a unique index on the link (recommended)
ALTER TABLE link_st
ADD UNIQUE INDEX s_t (student_id, teacher_id);
Or you can do the check in the insert statement (not really recommended, but it works).
INSERT INTO link_st (student_id, teacher_id)
SELECT s.id, t.id
FROM student s
INNER JOIN teacher t ON (t.id = 548)
LEFT JOIN link_st l ON (l.student_id = s.id AND l.teacher_id = t.id)
WHERE (s.id = 785) AND (l.id IS NULL)
This will only select 548, 785 if that data is not already in the link_st table, and will return nothing if that data is in link_st already. So it will refuse to insert duplicate values.
If you have a table schools, it depends if a student can be enrolled in multiple schools (unlikely, but lets assume) and teachers can be enrolled in multiple schools. Very possible.
table school
id unsigned integer auto_increment primary key
name varchar
table school_members
id id unsigned integer auto_increment primary key
school_id integer not null
member_id integer not null
is_student boolean not null
You can list all students in a school like so:
SELECT s.name
FROM school i
INNER JOIN school_members m ON (i.id = m.school_id)
INNER JOIN student s ON (s.id = m.member_id AND m.is_student = true)
When I join the Category table and
Business table to create the mapping
table would this then give me a table
which contains every possible business
and category relationship?
Yes.
Would I have to go through all listings (800,000) marking them as true or false?
No, you need to use the ON-clause to set join-conditions.
SELECT <columns> FROM categories as c
INNER JOIN mapping AS m
ON m.CategoryId = c.CategoryId
INNER JOIN businesses as b
ON m.BusinessId = b.BusinessId
You should use mapping tables when you are trying to model a many-to-many or one-to-many relationship.
For example, in an address book application, a particular contact could belong to zero, one or many categories. If you set your business logic that a contact can only belong to one category, you would define your contact like:
Contact
--------------
contactid (PK)
name
categoryid (FK)
Category
--------------
categoryid (PK)
categoryname
But if you wanted to allow a contact to have more than one email address, use a mapping table:
Contact
--------------
contactid (PK)
name
Category
--------------
categoryid (PK)
categoryname
Contact_Category
--------------
contactid (FK)
categoryid (FK)
Then you can use SQL to retrieve a list of categories that a contact is assigned to:
select a.categoryname from Category a, Contact b, Contact_Category c where a.categoryid=c.categoryid and b.contactid=c.contactid and b.contactid=12345;
select a.categoryname
from Category a
inner join Contact_Category c on a.categoryid=c.categoryid
inner join Contact b on b.contactid=c.contactid
where b.contactid=12345;
you only put the real relationships in the mapping table. so on average fi a business is in 2 categories, then in your example, there would only be 2000 records in the mapping table, not 800,000
"When I join the Category table and Business table to create the mapping table" you don't join those two tables to create the mapping table. You create an actual physical table.

Categories