table posts
table users
how would i count posts for specific user logged in. for example when user with id 3 is logged in it should show me 4 posts
I already did it for total posts count:
<?php
$post_query1 = "SELECT count(*) AS total FROM posts ";
$post_result1 = mysqli_query($db, $post_query1);
$post1 = mysqli_fetch_array($post_result1);
?>
Try below example :
select count(*) as total from user as u inner join post as p on p.id_user = u.id_user AND u.id_user = 3
If you want to get only the posts count for the particular user, say user with id = 3, your query should be this:
$query = "SELECT count(*) AS total FROM posts WHERE id_users = 3";
But if you want to get both the posts count as well as the user information and other post information, you will have to run a join query on both the users and posts table. Your query would now become:
$query = "SELECT u.*, p.*, count(p.id_posts) FROM users AS u JOIN posts AS p ON u.id_users = p.id_users WHERE p.id_users = 3";
Some Useful Notes
p.* - * is a wildcard character that means get all the columns in the posts table
u.* - * is a wildcard that means get all the columns in the users table
posts as p - AS is for aliasing. So, we are giving posts table a temporary name.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
Note: It is necessary that you have to join two/more tables only with the help of foreign key. Without the foreign key is is meaningless to join two or more tables
Reference 1: https://www.w3schools.com/sql/sql_join.asp
Reference 2: https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
As per the Question what you have asked to join the tables
Query:
SELECT * FROM TABLE 1 JOIN TABLE 2 ON TABLE1.id = TABLE2.id WHERE TABLE2.ID=3
Kindly replace TABLE1 & TABLE2 with the Tables that are to be joined and the id with the foreign key what you have specified in the Table.
Hope so this might be helpful for you to write your own code in future. Happy Coding :)
You have only to use a simple join.
SELECT count(*)
FROM USER u,
post p
WHERE p.id_user = u.id_user
AND u.id_user = 3
Related
I want get all users from users table and have a column summed up on all articles length written by all users from article table
Basically
Here is a code if I choose to run an SQL query for each loop (not good)
SELECT * FROM users
--loop
SELECT SUM(wordcount) AS totalwordcount FROM articles WHERE writer_id = user_id
I have used LEFT JOIN but I can only get a list of users with their user_id present on article table
SELECT users.name, SUM(article.wordcount) AS xox FROM users LEFT JOIN article ON users.id_usera = article.writer_id WHERE article.editor_status = 'finished' ORDER BY users.id_usera
With this query, I only get users with their user_id present in the article table but I want all users listed and NULL/empty returned if the user has no article with his/her id present
You need GROUP BY:
SELECT u.name, SUM(a.wordcount) AS xox
FROM users u LEFT JOIN
article a
ON u.id_usera = a.writer_id AND
a.editor_status = 'finished'
GROUP BY u.name;
SELECT users.name, SUM(article.wordcount) AS TotalWordCount
FROM users
LEFT JOIN article ON users.id_usera = article.writer_id
WHERE article.editor_status = 'finished'
GROUP BY article.writer_id
ORDER BY users.id_usera
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)
I have a table with two columns.
created_by | assigned_to
One is the person who create a "to do card", the other column is the person who is assigned to do it.
The columns are filled with id, for example; (1,2,3).
My question is how can i replace this id with the names that are saved in another table.
by far this is what i got.
SELECT tickets.*, users.Name, users.LastName
FROM tickets
LEFT JOIN users ON tickets.assigned_to = users.uid
AND tickets.id_usuario = users.uid
but when i try to print the name of the persona
Created by: <?= query['Name']; ?>
Assigned to: <?= query['Name']; ?>
but i got the same name in both columns.
Your current query only joins to users when the creator and assigned-to user ID are the same.
You'll need to join to your users table twice to retrieve the separate records. You do this by adding more joins...
SELECT
c_users.Name as created_by_name,
c_users.LastName as created_by_last_name,
a_users.Name as assigned_to_name,
a_users.LastName as assigned_to_last_name
FROM tickets t
INNER JOIN users c_users
ON t.created_by = c_users.uid
-- or t.id_usuario = c_users.uid, it is not clear from your question
INNER JOIN users a_users
ON t.assigned_to = a_users.uid
I've used INNER JOIN instead of LEFT JOIN as it doesn't seem feasible that you'd have broken relationships between the two tables.
I have two tables: publick_feed and users
I want to SELECT all from public_feed and also SELECT a three columns from users whose id is the same of user_id in public_feed
and assign the rows returned from public_feed to the column in users table ( correspondent)
I try this:
<?php
$sql = "
SELECT * FROM public_feed
WHERE user_id IN
(SELECT id FROM users) AND
(SELECT Firstname,Lastname,Avatar FROM users WHERE id IN(SELECT user_id FROM public_feed))
";
$query = mysqli_query($dbc_conn,$sql);
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
//echo rows with correspondent details from the users table
echo $row['user_id'];
}
}
<?
Please any help will be much appreciated.
Thank you.
Or version with left join in case if there is no user in public_feed, and you still want to fetch user data
SELECT
u.*, f.*
FROM
public_feed f LEFT JOIN
users u ON f.user_id = u.id;
Because author asked for explanation, here it is:
First we are going to use table name alias to make query shorter
public_feed f
and
users u
we are saying that want to refer to tables with an alias. Of course * means that we want to select all columns
SELECT users.*, public_feed.*
is equal to
SELECT u.*, f.*
Of course you can use any other letters as an alias
Next we are saying that public_feed.user_id must be equal to users.id. But when public feed entry does not exists just display columns with null values. This is why we are using LEFT JOIN instead of INNER JOIN. In general JOINS are used to fetch related data from more than one related tables.
ON keyword is saying values from which columns in the tables must be equal to satisfy the request
I think doing a join would be cleaner than using a complicated subquery:
SELECT u.Firstname,
u.Lastname,
u.Avatar,
COALESCE(pf.User_id, 'NA'),
COALESCE(pf.Post, 'NA'),
COALESCE(pf.Date, 'NA')
FROM users u
LEFT JOIN public_feed pf
ON u.Id = pf.User_id
I chose a LEFT JOIN of users against public_feed on the assumption that every feed will have an entry in the users table, but not necessarily vice-versa. For those users who have no feed entries, NA would appear in those columns and that user would appear in only a single record.
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