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!
Related
I'm trying to pull data from two tables for a 'related products' widget.
I've tried all the JOINS and UNIONS I can and still get nothing.
The first table (productdocs) stores documents. The second (prodrelated) shows when a product is related to a document:
productdocs
pdid (unique ID for the document)
pdname (name of the uploaded document)
prodrelated
prprodid (the ID for the PRODUCT)
pritemid (the ID for the document)
I am trying to output the productdocs.pdname for any documents that match up with the product's id. In otherwords, show the pdname when:
WHERE productdocs.pdid = prodrelated.pritemid
I would post my SQL code, but none of it has worked, so I think it would be pointless. I hope I explained this correctly given my frazzled brain - Any help greatly appreciated.
You can use a simple INNER JOIN for this, e.g.:
SELECT pd.pdid, pd.pdname
FROM productdocs pd JOIN prodrelated pr ON pd.pdid = pr.pritemid
WHERE pd.prprodid = <any_id>;
If you don't want to filter out any records, you can get rid of WHERE clause and it will output all the records.
Here's MySQL's documentation for JOIN.
Wow you guys are fast - thank you so much.
Darshan - thank you above all, I was able to make a few mods to what you wrote and it worked great. I tried to +1 your answer but maybe I don't have enough 'reputation'? Here is what I got working, thanks to you:
SELECT pd.pdid, pd.pdname
FROM productdocs pd
JOIN prodrelated pr
ON pd.pdid = pr.pritemid
WHERE pr.prprodid = '#url.prodid#'
In the future I will try to post some code example, but on this one I honestly tried at least 7 different queries so I had no idea which to post!
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.
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.
I am not that experience in sql so please forgive if its not a good question to ask,but i researched around almost for 3-4 days but no able to solve.
My problem is i have a table which have multiple image names in it,so what i have to do is whoever is the follower of a particular user i have to get the imaged from this table,so one user there can be multiple followers,so i have to fetch the images posted by all the followers.
Here is the subquery code snippet i am using.
SELECT id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email=ANY(SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com')
So the inner query here returns multiple values,for each value(being_followed) i have to fetch all the images and display it,but with this query each time i get only one image.I tried IN also but didnot work out.
Table structure:-
Outfitpic_list table
id|outfit_image|datetime|Email|image_title|description
Follower_table
bring_followed|follower
Please help,I am stuck..!!
Thank you..!!
I think your problem may be the = sign between "E-mail" and "Any". Try this statement:
SELECT
id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email IN
(
SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com'
)
It's the same statement, without the = sign, and the ANY keyword replaced with IN. (I cleaned it up a little to make it more readable)
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 )