Using the MySQL select statement - php

I would like to select the posts from users based on who the logged in user is following. What would I need to do? How do I use two different tables with one SELECT statement? I don't even know where to start.
I have 3 tables:
users
posts
followers
Thanks.

SELECT p.*
FROM followers f
JOIN posts p
ON p.author = f.following_id
WHERE f.user_id = $logged_in
ORDER BY
p.post_date DESC
I had to make up the field names as you haven't provided them.

Selecting from two tables is done using JOINs
http://dev.mysql.com/doc/refman/5.0/en/join.html
basically you select from two tables and define JOIN condition.
Assume you have two tables:
users with columns: user_id, user_name, online_state
posts with columns: post_id, user_id (user who posted this post), title, message
SELECT p.title, p.message FROM users u JOIN posts p ON u.user_id = p.user_id WHERE u.online_state = 'online'
join condition should be after ON, non-join condition after WHERE

I would go with the Join query as Quassonoi suggested in his answer, If you want to try an alternate solution, you can do it with subquery like this
SELECT P.PostId,P.Title,P.Body
FROM Post P WHERE P.CreatedById
IN (
SELECT FollowerID from Followers WHERE USER_ID=3
)
Replace 3 with the current user id. Assuming your table structure is something like this.
POST
PostId (int)
Title
Body
Followers
UserId (int)
FollowerId (int)

Related

Facing issues while fetching data from two different mysql tables using a single query..!

I have two tables, one for the posts and another for the users. I am fetching all posts from the 'posts' table and user data (who posted that post) from the tbl_users.
currently, I am using this query :
$query = $pdo->prepare("SELECT * FROM `posts`,`tbl_users` WHERE id = user_id_p ORDER BY `post_id` DESC");
$query->execute();
return $query->fetchAll();
it is working fine, it is fetching all the posts from the posts table and user data from tbl_users.
However, my issue is this that I don't want to fetch all posts, but I want to fetch only those posts which are posted by the specific user(for example by John only) and the user data for John only from the tbl_user.
(field Id from tbl_users and field user_id_p from the table posts are same in both the tables.)
Any suggestions or help?
Although your query is working, it is not at all efficient because it uses an implicit cross join which results in a very large resultset.
Use a proper INNER JOIN with a condition applied with WHERE:
SELECT u.*, p.*
FROM tbl_users u INNER JOIN posts p
ON u.id = p.user_id_p
WHERE u.id = ?
ORDER BY p.post_id DESC
Replace ? with the id of the user.
You can use JOIN for this. Example
select P.name, U.name from post P NATURAL JOIN user U;

Want to select data from different tables

I have two tables in database, named users(store user details) and posts(store post details). Now i want to get data from both tables. Like user_image from users and post description from post.
I am using this query
SELECT * FROM `users`AS u,`posts` WHERE u.user_id IN (SELECT user_id FROM `posts`)
But it returns duplicate data. I have 2 users and 3 posts but it returns 6 posts.
Try something like:
Select a.user_image, b.post_description from users as a join posts as b on a.user_id = b.user_id
Do an inner join & you shall get the desired result
In the above query a & b are alias for the two different tables. I you do not want to use alias you can also write it as users.user_image in your select statement.
Write the fields you want from both the tables in your select statements.
The below image will help you understand the inner join
Inner Join Circle for understanding
Use group by as below:
SELECT * FROM `users`AS u,`posts` WHERE u.user_id IN (SELECT user_id FROM `posts`) group by u.user_id
What about
Select * FROM user u right join posts p on u.id = p.user_id
?
if you want to get data from both tables you need to use joins.and you make sure the two tables are interlinked by primary keys
so use this can help
select user_image,post_description from users join posts on users.user_id=posts.user_id;

How to join 3 tables with different data between them?

I'm not too good with explaining things, apologies.
I have 3 tables that are similar to the below:
users
id
username
threads
id
title
user_id
lastpost_id
posts
id
content
thread_id
user_id
On a page listing forum threads, I want the username of both the thread author, and the last post author of that thread to be displayed, I'm attempting to achieve this in a single query.
My query looks like this:
SELECT t.*,u.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
ORDER BY t.id DESC
The first join enables me to get the username of the user id that started the thread.
The second join is what I'm not sure on, it can get me the user id but how do I get the username from that, as a 3rd join?
You can select the same table multiple times if you give it a different alias. You can give the fields aliases too:
SELECT
t.*,
tu.username as threadusername, /* Result field is called 'threadusername' */
p.*,
pu.username as lastpostusername
FROM threads t
INNER JOIN users tu ON t.user_id=tu.id /* thread user */
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users pu ON p.user_id=pu.id /* post user */
ORDER BY t.id DESC
You can join to a joined table like this:
SELECT t.*,u.username,u2.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users u2 ON p.user_id=u2.id
ORDER BY t.id DESC
Note, I haven't had time to test it, but it should work (at least in MySQL).
I don't know if I got it correctly, but as per my understanding you can have a inner query to fetch the thread ids and then have a outer query to fetch the posts based on the thread id, have a max on post id and group by user id. Also join to user to have the name. Hope that helps.

Complex Mysql query to combine 3 tables Data?

I have a table in which I store followers, I have another table in which I store friendships
Now I have third table which stores stream data.
Its a social network, there are many reasons so I don't wish to have one table for follower & friendships (Means facebook subscriptions/friends)
Can someone presents a way how should I query streams table to pick activities of both friends & followings ?
Any help would be really appreciated, thank you
Here is simple Database Scheme, its not really like this but almost!
Okay here is database tables schema please,
Followers table.
Row_ID
User_ID
Following_User_ID
Friends Table
Row_ID
User_ID
Friend_ID
Stream Table
Row_ID
User_ID
Contents_ID
Time
Type
What are you looking for is probably best done as two distinct results sets... or a union of the two.
Select "friend" as src, author, post from friends f inner join streams s on s.author = f.id
union
Select "follower" as src, author, post from followers f inner join streams s on s.author = f.id
This is just some pseudo coding but it should give you an idea of how to proceed. Without knowing your database schema, this is the best I can offer.
Edit:
This might be what your looking for then
select user_id, contents_id, time from (
select user_id, contents_id, time
from followers f inner join stream s on s.user_id = f.user_id and f.user_id = "username"
union
select user_id, contents_id, time
from friends f inner join stream s on s.user_id = f.user_id and f.user_id = "username"
) order by time desc
This will return the data in time order, descending.

Get results from my own and "friends" posts

I have a problem that I can't figure out myself. I've tried using LEFT JOIN etc but nothing seems to work. I'm using MySQL so you know.
I'm building a little blogportal for me and my friends and all users have their own blog.
database:
users:
id,
username,
password,
etc
blog:
id,
title,
text,
user_id,
etc
relations
follower_id,
following_id
I query my own blogposts like this:
SELECT * FROM microblog WHERE user_id = {$user_id} ORDER BY posted DESC
and i list my friends like this:
SELECT * FROM users, relations WHERE relations.follower_id = {$user_id} AND relations.following_id = users.id
That was the easy part. BUT.
I rather JOIN the tables somehow because I also want to list my friends blogposts inside my loop. But I don't just want the post to show, I also want some info about the user that posted that one so then I must get some info from the users table as well. And that's what bothers me! I can't figure it out.
In short: I want to list my own blog posts and all the users I'm friend with within my own loop. And I also want to display username and email beside the posts.
Hope you understand what I mean.
/Tobias
Sweden
How about?
select
u.username,
u.email,
m.title,
m.text
-- ... etc
from microblog m
inner join user u on m.user_id = u.id
where m.user_id = {$user_id}
or m.user_id in (select
following_id
from relations r
where follower_id = {$user_id}
);
From my perspective I would pull the user data separately, store them into an array and access them when needed. This should be better for performance and would definitely be simpler.
select * from blog b, relations r
where b.user = $user_id or ( b.user = r.follower_id and r.following_id = $user_id )
order by posted desc;
Not sure if I reversed follower/following.
Try this?
SELECT m.*
FROM microblog m
INNER JOIN users u ON m.user_id = u.user_id
LEFT JOIN relations r ON r.following_id = m.user_id
WHERE m.user_id = {$user_id}
OR (r.follower_id = {$user_id} AND NOT IsNull(r.follower_id))
ORDER BY posted DESC

Categories