Select from multi tables and return all - php

I have 4 tables:
posts [post_id post_title post_body post_date post_by post_accepted]
users [user_id user_name user_pw]
comments [comment_id comment_user comment_co comment_post comment_date]
categories [categorie_id categorie_name]
Each table contain a data all data are belong to table posts:
categories<-posts
posts<-users
posts<-comments<-users
I want to get posts with id post_id and get with it a comments and who post it and get the category name and id.
I tried but I get the post but not all comments or if the post does not have comment it will no appear.
This my SQL query:
SELECT COUNT(comment_id),comments.*,categories.*,users.*,posts.*
FROM posts
JOIN categories on (posts.post_id = categories.categorie_id)
JOIN users on (posts.post_by = users.user_id)
LEFT JOIN comments on (posts.post_id = comments.comment_post)
WHERE posts.post_id='34'
AND posts.post_accepted = '1' ;

Try add GROUP BY users.id to your query

Related

What Sql Join can I use to combine my three tables

I made a query that user can see all the post of active users but not of those inactive, but also they should not see the post of users they blocked or blocked them how can I do that?, the block_users table has block_by_userid and blocked_userid column.
I tried INNER JOIN the post table with members table which every inactive users post cannot be seen anymore., How will I combine the block_users table?
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active'";
you might try FULL OUTER JOIN
the idea it to get all items in both tables member and block_users and then filter the data using where clause, i am sorry if i miss using the fields name , so please check the tables names, i assume block_users.block_by_userid contained the blocked user id if not use the correct field
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
FULL OUTER JOIN block_users ON Members.User_id = block_users.user_id
WHERE Status='active'
AND
WHERE block_users.block_by_userid != Members.User_id";
Suppose I am doing this for a user xyz whose user_id is 123 then below is a query which will return expected output for user 123.
Query:
SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active' and post.poster_user_id NOT IN(select block_by_userid from block_users where blocked_user_id = 123 UNION select blocked_user_id from block_users where block_by_userid = 123)

Tricky query: getting Count of one column with 2 conditions for another distinct column

I am struggling with a challenging query.
I have 2 tables: posts, answers
posts has ID, PID, name
answers has ID, PID, approved
ID is the user ID, PID is the post ID.
What I am trying to do is list all the post names (posts.name) and how many unique people (IDs) have replied to their posts. The trick is that I only want to count replies that are approved (answers.approved = 'Y') AND I do not want to count the person who created the post, so (post.ID != answers.ID).
So the results should show something like:
Name People with Approved Replies
Name 1 10
Name 2 7
My current code is a mess and the wrong approach. It only gives one result and the count of replies is way off/far too high. But here is what I have currently:
$results = $dbh->prepare("select COUNT(DISTINCT answers.ID) AS reply,
posts.ID,
posts.PID,
posts.name,
answers.PID,
answers.approved
FROM answers
LEFT JOIN posts ON answers.PID=posts.PID
WHERE (answers.approved = 'Y') LIMIT 10
GROUP BY answer.ID");
$results->execute();
$row = $results->fetchAll(PDO::FETCH_ASSOC);
I think this query should do what you want
SELECT
p.name,
p.id,
p.pid,
(SELECT COUNT(DISTINCT id)
FROM answers
WHERE answers.pid = p.pid
AND answers.approved = 'Y'
AND answers.id != p.id) as reply
FROM posts p
This will select posts name , id , user id and count of distinct approved answers

MYSQL/PHP join many-to-many, fetch posts with their all categories

I have 3 table
blogposts table, categories table, joins table.
SELECT post_id,
post_title,
post_text,
post_poster,
post_date,
post_slug,
category_name,
user_name
FROM blogposts_categories_join
INNER JOIN blogposts ON post_id = bcj_post_id
INNER JOIN categories ON bcj_category_id = category_id
INNER JOIN users ON post_user = user_id
GROUP BY post_id
This is my query and I want to fetch posts for home page. everything is working but, the fetched data have only one category and I want to make something like this:
Posted in: general, news, health
How must I change my query to get posts, with all categories?
Since you're already grouping by post, you could just use a GROUP_CONCAT to get all the categories, comma separated, something like (the untested);
SELECT post_id,
post_title,
post_text,
post_poster,
post_date,
post_slug,
GROUP_CONCAT(category_name) category_names,
user_name
FROM blogposts_categories_join
INNER JOIN blogposts ON post_id = bcj_post_id
INNER JOIN categories ON bcj_category_id = category_id
INNER JOIN users ON post_user = user_id
GROUP BY post_id

Queries from Diffrent Tables How to Join Suggest PLease (PHP)(SQL)

I need help regarding JOIN tables to get category name & author name from other tables.
for articles site I have Three Tables
articles
categories
users
Articles Table structure :
id
title
slug
content
category
author
date
I save category ID & user ID in articles table with each article
While Displaying Articles for a category I use this:
(just some draft idea not full code)
localhost/testsite/category.php?cat=category-slug
$catslug = ($_GET["cat"]);
//GET CAT ID from category table from slug
$qry = "SELECT * from category WHERE slug='$catslug';
$res = mysql_query($qry) or die("Error in Query");
$ans = mysql_fetch_array($res);
$cid = $ans['id'];
$catname = $ans['title'];
<h2><?php echo $catname; ?></h2>
//after getting cat-id query to get article of that ID
$aqry = select * from article where category=$cid ORDER BY date";
$ares = mysql_query($aqry) or die("Error in Query");
$aans = mysql_fetch_array($ares))
$aid = $aans['author'];
//then another query to get author name from users
select username from users where id=$aid
I m learning PHP & not much familiar with JOIN statement & combining queries
need help/suggestions hw can I achieve same with JOIN tables instead of different queries to get catname and author name from tables.
Thanks
This should do what you want
SELECT distinct c.title, U.Username
from category C join article A on A.category=C.id
join users U on U.id=A.author
WHERE C.slug= :catslug
Assuming Category id is foreign jey in article table
Try this query
select username from users
where id in (
select author from category cat
inner join article art
on cat.category_id =art.category_id
where cat.slug= $cat
order by art.date desc )
$q = "SELECT article.*
FROM article
LEFT JOIN category
ON article.category = category.ID
LEFT JOIN users
ON article.author = users.ID
WHERE article.slug = :slug";
:slug is where you would insert (bind if you're using PDO) $_GET['slug']
You can do some different thing with a SQL request. You can do some join in your SQL request but you can also do another SELECT statement in your request Like
SELECT SOMETHINGS FROM A_TABLE WHERE (SELECT ANOTHER_THING FROM ANOTHER_TABLE WHERE VALUE =1
But this statement will only work if you have 1 result in your second request
If you want to join two table with some value, you'll have to do it like this
SELECT something FROM a_table AS alias1 JOIN another_table AS alias2
ON alias1.value1 = alias2.value1 and .....
You can compare all the value that you want from one table to another and you can also join more than two table and the ON key word is not requested by sql syntax you can just do
SELECT * FROM table_1 join table_2
and it will show you all thje data from two table but be sure that this is the data you want this kind of little query can have some big result and slow down your app
you can read more there http://dev.mysql.com/doc/refman/5.0/en/join.html
First off, you should write a stored proc... but here's how you would get articles by categoryID that includes both the category name and user name.
Given the following table structures:
article
---------
articleID <- primary key
title
slug
content
categoryID <- foreign key
userID <- foreign key
createdDT
category
--------
categoryID <- primary key
categoryName
user
--------
userID <- primary key
userName
Here's how to write the query using joins:
SELECT a.title, a.slug, a.content, a.createdDT, c.categoryName, u.userName
FROM dbo.article a
JOIN dbo.category c on a.categoryID = c.categoryID
JOIN dbo.user u on a.userID = u.userID
WHERE a.categoryID = #categoryID
Here's an article from Microsoft on JOINs - http://msdn.microsoft.com/en-us/library/ms191517.aspx

Getting Value From A Third Table

SELECT POSTS.*
FROM POSTS
LEFT JOIN SUBSCRIBERS
ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
WHERE POSTS.AUTHORID = ?
OR SUBSCRIBERS.SUBSCRIBERID = ?
ORDER BY POSTID DESC
LIMIT ?
The above is the query I'm using and this will select posts from the profiles a user is subscribed to. Now this works fine, but now I want to grab another column from another table.
In my third table USERS, I have an "AVATARID" which I want to access.
In my fetch loop for this query, it echos out the username of the post author, and the post body. What I want it to do is also echo out the avatarID of the user who wrote the post. I tried adding in another query inside my while loop, but I find that sloppy, and it also doesn't work :S
So, simple question: How do I access the AvatarID from the table USERS with the USERID of the AUTHORID from the post?
Something like...
SELECT POSTS.*, USERS.AVATARID
FROM POSTS
LEFT JOIN SUBSCRIBERS ON POSTS.AUTHORID = SUBSCRIBERS.PROFILEID
JOIN USERS ON POSTS.AUTHORID = USERS.USERID
WHERE POSTS.AUTHORID = ?
OR SUBSCRIBERS.SUBSCRIBERID = ?
ORDER BY POSTID DESC
LIMIT ?

Categories