database structure for google plus circles? - mysql

I know for sure that Google does not use mysql, but in my case I happen to work on a project using mysql and has features that are very similar to circles:
user can belong to many circles
user can be add/removed from circles
posts can be public or can be shared to circles/individual users
if a post is shared to a circle, and new user is added to this circle then this user can also view the post.
If a post is shared to a circle, and an user is removed from this circle then: a. he/she can still view the post if he/she replied in the post b. he/she cannot view the post anymore otherwise
As you can already see, with the above requirements there are a lot going on in the database. If I really share both to circles and individual users, i will probably need 2 One2Many tables. If I share only to individual users by getting the list of users for each circle at the very beginning, then I run into troubles later on when users edit these circles.
Currently, my get-around hack is to share to circles only, even for each individual user I create a 1 user only circle.
So my current database tables look a bit like this:
circle_to_user:
id
circle_id
user_id
friend_id
post:
id
user_id
is_public
post_to_circle
id
post_id
circle_id
To query out the list of posts a user can view, the query is rather complicated and consists of multiple joins:
$q = Doctrine_Query::create()
->addSelect('s.*')
->addSelect('u.id, u.first_name, u.last_name, u.username, u.avatar')
->from('UserStatus s')
->leftJoin('s.User u')
->orderBy('s.created_at DESC');
$userId = sfContext::getInstance()->getUser()->getUserId();
if ($userId == $viewUserId) {
$q->orWhere('s.user_id = ?', $userId);
$q->orWhere('s.user_id IN (SELECT DISTINCT cu1.friend_id FROM CircleUser cu1 WHERE cu1.user_id = ?) AND s.is_public = ?', array($userId, true));
$q->orWhere('s.id IN (SELECT DISTINCT(us2.id)
FROM
UserStatus us2 INNER JOIN us2.UserStatusCircles usc2 ON usc2.user_status_id = us2.id
INNER JOIN usc2.Circle c2 ON c2.id = usc2.circle_id
INNER JOIN c2.CircleUsers cu2 ON cu2.circle_id = c2.id AND cu2.friend_id = ?)', $userId);
} else {
$q->orWhere('s.user_id = ? AND s.is_public = ?', array($viewUserId, true));
$q->orWhere('s.id IN (SELECT DISTINCT(us1.id)
FROM
UserStatus us1 INNER JOIN us1.UserStatusCircles usc1 ON usc1.user_status_id = us1.id AND us1.user_id = ?
INNER JOIN usc1.Circle c1 ON c1.id = usc1.circle_id
INNER JOIN c1.CircleUsers cu1 ON cu1.circle_id = c1.id AND cu1.friend_id = ?)', array($viewUserId, $userId));
$q->orWhere('s.id IN (SELECT DISTINCT(us2.id)
FROM
UserStatus us2 INNER JOIN us2.UserStatusCircles usc2 ON usc2.user_status_id = us2.id AND us2.user_id = ?
INNER JOIN usc2.Circle c2 ON c2.id = usc2.circle_id
INNER JOIN c2.CircleUsers cu2 ON cu2.circle_id = c2.id AND cu2.friend_id = ?)', array($userId, $viewUserId));
}
I hope that the above info is not too long, I just want to give lots of details. My questions are:
Given the above requirements, is my implementation good enough, or is there anything I should change to make it better?
I want to search for articles regarding this type of specific database design problem but could not find much, is there any technical term for this type of database design
Would you suggest any alternatives such as using another type of database, or perhaps index the posts with a searchengine like elastic and let it handle the search instead of using mysql?
Thank you very much for reading until this point, if you find anything I should change in the question to make it easier to follow and to answer, please do let me know.

while your single user circle sounds like a nice try, how will you go about distinguishing it on the way out? when you see a post is shared to a circle, how do you know if that circle is a genuine one or a single user? because i imagine you want to display them differently on the interface. and you'd probably need to know when you fetch the fake circles from the db that the user should not be able to edit them.
while you might get away with avoiding linking to users you now have to handle special circle cases. i'd say go with your 2 x 1-* tables that link a post to multiple circles and separately to multiple users.
perhaps to encourage you to review your intention and leaving aside the 'friend' relationship that may add a special case, as i see it you're more or less looking to: fetch all posts that are public, or are shared with my user, or are shared with a circle i am in, or are posts that i replied to. that isn't too complicated i don't think and you don't have to get a list at the beginning or anything.
(on a related note, multiple JOINs is not a problem that stands out. more importantly you have multiple sub-queries. usually that is bad news. in most cases they can be reworked as normal joins and usually more cleanly).

This kind of problem is mostly not solved with a relational model , i think google uses the datastore , which then sits on bigtable , cassandra and hadoop equivalent.

I am also in same problem but i can suggest you something that i allready covered/completed that dont make two tables for post instead of that add column in Posts table named with/circle_id.
And i also i want to tell you that add a/or more default circle entry(specifically Public and also All Friends/Circles in Circles table.
Now your Post Pickup query will be like this.
$id=$_SESSION["loged_in_user_id"];
$sql="SELECT * FROM `posts` as p,`circles` as c WHERE c.circle_create_id=$id and (p.with=c.id or p.with=1)";//p.with columns contain circle id and as i tell first entry will be public
$sql_fier=mysqli_query($sql);
/*-------I think you know how to manipulate fetched data---------*/
Connect me on social network http://www.funnenjoy.com (signup/login is required )

Related

MYSql multiple join query kando

I have a question for school that I can't quite figure out.
For each card on the board with the name “Product launch”, list the details of the card, the title of the column it is on, who created the card and member(s) that the card is assigned to.
I'm trying to work through this put not getting anywhere really.
select card.description, (select user.UserName where card.Creator = user.userID)
FROM card, user, board, `column`
JOIN board ON board.BoardID=`column`.boardID
where board.boardname = "Product launch"
Any help would be appreciated
10/10 for honesty in admitting that you are asking the internet to do your homework for you ;-) You will find that you are more likely to get help if you show clear signs of trying to help yourself.
If you are struggling then start by taking small logical steps and building it up progressively. Start with just retrieving the board with the given name (yes, I know you have already done this) -
SELECT *
FROM `Board`
WHERE `Board`.`BoardName` = 'Product launch'
then the next step is to satisfy the "for each card on the board" requirement. Based on your ERD we know we need to get the Columns to get to the Cards, so add Columns next -
SELECT `Board`.`BoardName`, `Column`.`ColumnTitle`
FROM `Board`
INNER JOIN `Column`
ON `Board`.`BoardID` = `Column`.`BoardID`
WHERE `Board`.`BoardName` = 'Product launch'
then the Cards -
SELECT `Board`.`BoardName`, `Column`.`ColumnTitle`, `Card`.*
FROM `Board`
INNER JOIN `Column`
ON `Board`.`BoardID` = `Column`.`BoardID`
INNER JOIN `Card`
ON `Column`.`ColumnID` = `Card`.`ColumnID`
WHERE `Board`.`BoardName` = 'Product launch'
then continue the process to add the Creator and then the member(s) via CardAssignment. You may want to look at GROUP BY and GROUP_CONCAT when adding the member(s).
If you continue to struggle don't just say I cannot figure it out. Have a go and then come back with details of what you have tried and what hasn't worked as you expected. Researching and having a go are huge parts of the learning experience.

SQL Is this Outer or Inner Join and how to join on Array

Seemed simple when I started and have done this before, now I confused myself and at a road block.
Have two tables: News_Table and a People_Table. Under the News_Table there is a field: News_People_Contributed and it has the ID's of the People_Table in array format (1,4,7,10) thus Four People contributed. I am creating a search parameter that looks up News_Header AND News_People_Contributed and can't figure how to create the search column.
News_Table
News_ID
News_Header
News_People_Contributed
People_Table
People_ID
People_First_Name...
Is it something like...
Select*
From News_Table
Left Join News_Table
On People_Table.People_ID IN (News_Table.News_People_Contributed)
Where Search_Param Like '%News_Header%' OR Search_Param Like '%People_First_Name%'
The problem is (News_Table.News_People_Contributed) is a string and the ID's are not. Plus I may not have people contributed etc. To make the issue even more complex, I'm doing this in MS Access instead of MySql, so have to code it "old school" sql for work around.
Perform a cross join and filter on matches in the string list. It says nothing about efficiency or form (as already commented on), but it works.
SELECT *
FROM News_Table, People_Table
WHERE InStr([News_People_Contributed],CStr([People_ID])) > 0;
This only answers part of the problem: The join -- the issue everyone seemed concerned about in the initial comments. There are not enough details about about the Search_Parameter to provide help on that. Supply more detail if you need more help there.

INNER JOIN query producing results in the thousands

I hope I explain this right, but I'm having some issues with an INNER JOIN query I am building. Let me give it a shot: I have a friends table in which there are a user1 and a user2 field, both of which can be a friend of the user, depending who was the inviter, the user or the friend. Now, all these friends are of course users themselves as well and they post messages on their respective pages. All of these messages get stored in a table surprisingly called "messages". I want a user to be able to see all the messages all of his friends have posted and to establish this, I created the following INNER JOIN query:
SELECT friends.user1, friends.user2, messages.message
FROM friends
INNER JOIN messages
WHERE (friends.user1 = 'Panda' OR friends.user2 = 'Panda') AND (friends.user1 != 'Panda' OR friends.user2 != 'Panda') AND messages.message != '' AND friends.accepted = '1'
(Panda being a test user ofcourse).
What happens is that it indeed selects all of Panda's friends and it selects all of the messages those friends have posted, however, I get ten thousands of results with this query as ALL of the friends have a message one friend has posted in the results. Let me try and clarify this:
Suppose Panda's friend GalwayMonster has posted: "Lees dit boek!".
In the results of the above query it will show up like this:
GalwayMonster "Lees dit boek!"
PaddyPower "Lees dit boek!"
Brother "Lees dit boek!"
Monkey "Lees dit boek!"
(unfortunately SO does not let me post a screenshot as I don't have enough reputation yet, so I guess this will have to do for now - sorry about that)
and so on - every friend it finds, it adds the message GalwayMonster has posted to it, and it does so with each and every post made by any of the other friends.
Obviously I want the correct message to show up at the friend who posted it and if a friend hasn't posted anything, I don't want that friend to show up at all.
What am I doing wrong with this query? Is there something I need to add to have it show the correct message belonging to a friend only with that friend?
I hope I have made this clear enough, but if you have any additional questions, just let me know. Thanks a million!
Try using
messages.message IS NOT NULL
Instead of
messages.message != ""
These mean two different things. Maybe this will fix your issue but if you could provide some sample data from the tables and what columns are in the tables that would help. I can update the answer if you provide that if this doesnt fix it.
You need to look at the relationship between the friends and messages tables and adjust your query so that it only pulls back the messages for the friends that you want to see. You will probably want to use an on condition added to your join for this.
At the moment it looks as though the only limitation you are applying to messages is that the message is not blank.
Without seeing the columns in your tables however it is not possible to provide any further pointers.
I think I fixed it. Not really sure actually what the problem is, it gives the desired result (I verified that the result was correct). I changed it into following, just so it may be helpful to somebody else as well:
SELECT friends.user1, friends.user2, messages.message, messages.username, messages.remark, messages.posttime
FROM friends
INNER JOIN messages
WHERE messages.username != 'Panda' AND (messages.username = friends.user1 OR messages.username = friends.user2) AND (friends.user1 = 'Panda' OR friends.user2 = 'Panda') AND messages.message != '' AND messages.remark = ''
Still seems a bit long of a query though, but it works and it will have to do for now. A friend of mine suggested to have a look at the UNION or UNION ALL statement to see whether it does something. Anyway, thank you all so much for putting in the effort to help me :) Cheers from Ireland!

Mysql LEFT JOIN remover

I have an comment field where users can post questions and answers to each other.
The $row looks like this:
$posts_sql = "SELECT * FROM posts LEFT JOIN users ON posts.post_by = users.user_id WHERE posts.post_topic = " . mysql_real_escape_string($_GET['id']);
This is what it gets after they talk to eachother in the field:
User 1 writes "What can I Help you With?".
User 2 answers "Nothing Special".
User 3 says: "Okay, welcome back.".
User 1 reply again to the answer User 2 just gave, but this Second comment User 1 did is going straight to the top again, skipping User 2's answer and puts the comment over it. Like this:
User 1: What can I help you with?
User 1: Okay, welcome back.
User 2: Nothing special.
I want it to go like this:
User 1: What can I help you with?
User 2: Nothing special.
User 1: Okay, welcome back.
I don't know how to remove the LEFT JOIN users ON ( I guess that's the script that does this )
I want it to be: ORDER BY post_date DESC, comment after comment, not moving the Username's ID to stick with it.
How can i Change the following code to make it proper?
$posts_sql = "SELECT * FROM posts LEFT JOIN users ON posts.post_by = users.user_id WHERE posts.post_topic = " . mysql_real_escape_string($_GET['id']);
I Hope I was Specific enough, please let me know if there's anything else you need to know about the table or code.
The left join links the friendly name of the user with the message so the display can be
User 1: What can I help you with?
Without the join all you could display is the user'd ID
1143245: What can I help you with?`
Obviously less than ideal. There is no reason you couldn't just append the order by after the where clause
$posts_sql = "SELECT * FROM posts LEFT JOIN users\
ON posts.post_by = users.user_id\
WHERE posts.post_topic = ".
mysql_real_escape_string($_GET['id']).
" ORDER BY post_date";
Disclaimer: The usual caveats about protecting against SQL injection, URL manipulation, upgrading to mysqli apply. But if you want to shoot yourself in the foot, I won't stop you.

MYSQL Selecting multiple values from the same column as a row

I have two tables
table COMMUNITY
id,
name,
etc.
table PROPERTY
id,
community_id,
type,
price,
rate,
etc.
There are four possible property types and a community can have info for one or more of the different types.
I am trying to figure out how to combine the information for each community into one row.
For instance I might want to get a row which includes
community.id, community.name, condo.price, condo.rate, town_home.price, town_home.rate
Of course there aren't tables for condo or town_home, the property type is represented in the property table by a column and a community can have multiple property rows.
My first thought was to use multiple joins on the table with aliases, but I can't seem to get anything that works properly.
Any suggestions?
You can use left join for this.
SELECT c.id, c.name, condo.price, condo.rate, town_home.price, town_home.rate
FROM Community c
LEFT JOIN Property condo ON condo.community_id = c.id AND condo.type = 'condo'
LEFT JOIN Property town_home ON town_home.community_id = c.id AND town_home.type = 'town_home'
I am the kind of person who doesn't like much to use joins, might be because I don't see much reason as for use them or as I wouldn't need it.
By any means, this is the way I would put it:
As you have a link between the two tables, you are able to use them to bring you the data you need, as long as you have this link you can bring whatever field you want.
So you said you wanted the fields:
community.id, community.name, condo.price, condo.rate, town_home.price, town_home.rate
SELECT
community.id,
community.name,
condo.price,
condo.rate
FROM
community, property condo
WHERE
community.id = condo.community_id;
This should solve it.
Try this:
SELECT * FROM community LEFT OUTER JOIN property ON community.id = property.community_id;
This should join the two tables on the ID field, so you should have one complete row with all of the information. if anything is null, it should be present in the row, as well. If multiple properties are listed with the same community ID, they should all come up in the result.
PS - I use PostgreSQL and not MYSQL so the syntax might be a bit different. Let me know how it works!