Mysql LEFT JOIN remover - mysql

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.

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.

Get All Tickets in OSticket

Can someone help me figure out how I can retrieve all tickets? I read online and saw that there's no API to do this yet? I also read that i can write some sql code to retrieve them?
My objective is: Check OSticket to see if the ticket with the same subject is created more than 3 times, then to basically alert me ( for now it can just be a message in Powershell that says it, as I'm scripting in PS).
For that I need to retrieve all tickets in the OSticketDB. Since I just have it locally for now, I have a sql DB setup but I don't see something along the lines of ost_tickets? Not sure how I can retrieve tickets that have been duplicates from same subject.
I'm not sure I understand your question correctly. But here is SQL query, that will return all tickets, where subject has occurred more than 3 times.
SELECT
cdata.ticket_id,
cdata.subject,
ticket.number,
subjectstable.subjectcount
FROM
osticketdb.ost_ticket AS ticket
INNER JOIN osticketdb.ost_ticket__cdata AS cdata ON ticket.ticket_id = cdata.ticket_id
INNER JOIN
(SELECT subject, COUNT(*) as subjectcount FROM osticketdb.ost_ticket__cdata GROUP BY subject) AS subjectstable
ON subjectstable.subject = cdata.subject
WHERE subjectstable.subjectcount > 3

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!

Complex Query for Displaying comments based on friends added

I have a very big problem with my website. I have a form, more like a text box used in submitting comments, that not the problem. The problem is displaying the comments. I want to display comments based on the friends a user added like the way facebook, twitter does.
I have 3 tables:photo_tb, comment_tb, friendship_tb.
The friendship_tb contains columns name, friend. name stores your email and friend stores the email of the person you add....
I need the photo_tb to get the picture of the person making the comment and I use a mysql join successfully.
In my comment_tb...i get the email of the person making the comment in my commentname column and comment made by the person...
I want to to show comment by ffriendship like if Mr A adds Mr B and Mr c..when Mr A logs on he should only get comments by both Mr B and Mr c and his comments doe not comments from Mr G or H.
This is what i have so far
SELECT
comment_tb.comment_id
, comment_tb.comname
, comment_tb.comment
, comment_tb.time
, photo_tb.name
, photo_tb.photo
, friendship.name
, friendship.member
FROM comment_tb, photo_tb, friendship
WHERE
comment_tb.comname=photo_tb.name
and friendship.name = colname
The colname is a variable for MM_Username ,the session variable when you log in is meant to display comments related to you.
The sql statement attaches the picture to each comment name successfully but doesn't limit the comment to friends added.
Add and friendship.member = comment_tb.comname.
BTW, it would be nice if the column names in your SQL matches what you said in the description. I'm just guessing that friendship.member is what you called friend in the text.

database structure for google plus circles?

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 )