SQL join 2 tables together - mysql

I have a problem with joining 2 tables
Here is my first table with the name "users"
user_id user_username user_password user_name
1 admin admin123 john
3 test test123 alex
And here is my second table "posts"
post_id post_content post_userid
1 Lorem ipsum.. 1
2 Second post .. 3
I wanna show it like this:
post_id | post_content | post_userid | user_id | user_username | user_password | user_name
--------|----------------|-------------|---------|---------------|---------------|---------------
1 | Lorem ipsum.. | 1 | 1 | admin | admin123 | john
2 | Second post .. | 3 | 3 | test | test123 | alex
I've allready tried
SELECT * FROM posts INNER JOIN users ON(post_userid = user_id)
but that only shows the first post.
Then i tried
SELECT * FROM posts FULL OUTER JOIN users ON(post_userid = user_id)
that came out like this
post_id | post_content | post_userid | user_id | user_username | user_password | user_name
--------|----------------|-------------|---------|---------------|---------------|----------
1 | Lorem ipsum.. | 1 | 1 | admin | admin123 | john
2 | Second post .. | 3 | NULL | NULL | NULL | NULL
NULL | NULL | NULL | 3 | test | test123 | alex

SELECT * FROM posts AS p LEFT JOIN users AS u ON u.user_id = p.post_userid

SELECT
post_id,
post_content,
post_userid,
user_id,
user_username,
user_password,
user_name
FROM posts
INNER JOIN users ON user_id = post_userid

since i think your select should work, i suspect character fields for your ids. thus i suggest you try this join:
SELECT *
FROM posts
INNER JOIN
users
ON (rtrim(ltrim(post_userid)) = ltrim(rtrim(user_id)));
if that works, you should clean up your ids like this:
update posts
set post_userid = ltrim(rtrim(post_userid));
update users
set user_id = ltrim(rtrim(user_id));
also you should check whether your application inserts those blanks/whitespaces into your tables and stop it doing so.

Select * From posts p
INNER JOIN users u
ON u.user_id = p.post_userid

Related

How to limit and search number of joined rows from table in multiple joins in mysql

i have a following tables in MySQL database:
+------------------------+
| Users |
+----+--------+----------+
| id | name | role |
+----+--------+----------+
| 1 | Martin | admin |
+----+--------+----------+
| 2 | George | admin |
+----+--------+----------+
| 3 | John | employee |
+----+--------+----------+
+-------------------------+
| Forms |
+----+--------------------+
| id | type |
+----+--------------------+
| 10 | marketing_form |
+----+--------------------+
| 11 | client_survey_form |
+----+--------------------+
| 12 | client_survey_form |
+----+--------------------+
+---------------------------------------------+
| UsersAssignToForms |
+----+---------+---------+--------------------+
| id | user_id | form_id | additional_comment |
+----+---------+---------+--------------------+
| 20 | 1 | 10 | Lorem ipsum... |
+----+---------+---------+--------------------+
| 21 | 2 | 10 | Lorem ipsum.... |
+----+---------+---------+--------------------+
| 22 | 3 | 10 | null |
+----+---------+---------+--------------------+
| 23 | 3 | 11 | null |
+----+---------+---------+--------------------+
I would like to have result:
+---------+---------+------------+--------------------+--------------------+
| user_id | form_id | first_name | form_type | additional_comment |
+---------+---------+------------+--------------------+--------------------+
| 1 | 10 | Martin | marketing_form | Lorem ipsum... |
+---------+---------+------------+--------------------+--------------------+
| 3 | 11 | John | client_survey_form | null |
+---------+---------+------------+--------------------+--------------------+
| null | 12 | null | client_survey_form | null |
+---------+---------+------------+--------------------+--------------------+
First of all i would like to limit number of users returned from join query (one user per one form). If user with admin role is assigned to form i would like to display this user (prioritize admin role over employee role) and limit number of returned users to 1, if admin is not assign, but employee is assigned query should return this user, if no-one is assign query should return nulls (left or right join probably).
I saw this question on stackoverflow - MySQL JOIN with LIMIT 1 on joined table, but unfortunately first answer has n+1 issue and rest of answers was made with simple one join. For my purposes i need to join more tables but wouldn't like to design this tables above to clarify what i would like to achieve, but it's very important.
So my query will looks like probably:
SELECT u.id, f.id, u.name, f.type, uf.additional_comment, [more selects from other tables...] FROM Forms as f
LEFT JOIN Users as u ON ......
INNER JOIN UsersAssignToForms as uf ON .....
[here i would like to put more and more inner joins.....]
In MySql >= 8.0 you can number the rows using some criteria (for each Form starting from one and order by u.role ASC and u.id ASC), then you can filter rows with number one:
WITH sq AS (SELECT u.id AS user_id, f.id AS form_id, u.name, f.type, uf.additional_comment,
ROW_NUMBER() OVER (PARTITION BY f.id ORDER BY u.role ASC, u.id ASC) AS num
FROM Forms AS f
LEFT JOIN UsersAssignToForms AS uf ON f.id = uf.form_id
LEFT JOIN Users AS u ON u.id = uf.user_id)
SELECT *
FROM sq
WHERE num = 1;
Before MySql 8.0 you can try something like this (the idea is the same but with different implementation):
SELECT sq2.user_id, sq2.form_id, sq2.name, sq2.type, sq2.additional_comment
FROM (
SELECT
sq1.*,
#row_number:=CASE WHEN #form_id = sq1.form_id THEN #row_number + 1 ELSE 1 END AS num,
#form_id:= sq1.form_id
FROM (SELECT u.id AS user_id, f.id AS form_id, u.name, f.type, uf.additional_comment
FROM Forms AS f
LEFT JOIN UsersAssignToForms AS uf ON f.id = uf.form_id
LEFT JOIN Users AS u ON u.id = uf.user_id
ORDER BY f.id ASC, u.role ASC, u.id ASC) AS sq1
ORDER BY sq1.form_id) AS sq2
WHERE sq2.num = 1;

MySQL - Left Outer Join not updating original table

I created a toy dataset where I am trying to count the number of posts for each user. I seem to be getting the correct count values but the count column in the users table is not updated with the values.
I'm new to mysql and very confused! Can somebody tell me what I'm doing wrong?
users:
+---------+------+-------+
| user_id | user | pword |
+---------+------+-------+
| 1 | Amy | abcd |
| 2 | Jess | efgh |
| 3 | Lori | ijkl |
+---------+------+-------+
posts:
+---------+-------------+------+
| post_id | post | user |
+---------+-------------+------+
| 1 | hi | Lori |
| 2 | hello | Jess |
| 3 | hello again | Jess |
| 4 | and again | Jess |
+---------+-------------+------+
mysql> ALTER TABLE users ADD COLUMN post_count INT;
mysql> SELECT u.user_id, COUNT(p.user) AS post_count FROM users u LEFT JOIN posts p ON u.user LIKE p.user GROUP BY u.user_id;
+---------+------------+
| user_id | post_count |
+---------+------------+
| 1 | 0 |
| 2 | 3 |
| 3 | 1 |
+---------+------------+
mysql> SELECT * FROM users;
+---------+------+-------+------------+
| user_id | user | pword | post_count |
+---------+------+-------+------------+
| 1 | Amy | abcd | NULL |
| 2 | Jess | efgh | NULL |
| 3 | Lori | ijkl | NULL |
+---------+------+-------+------------+
Thanks!!
Please try the following...
UPDATE users
JOIN ( SELECT u.user_id AS user_id,
COUNT( p.user ) AS post_count
FROM users u
LEFT JOIN posts p ON u.user LIKE p.user
GROUP BY u.user_id ) postCountFinder
ON users.user_id = postCountFinder.user_id
SET users.post_count = postCountFinder.post_count;
This question takes your list of users and post counts obtained from the following...
SELECT u.user_id,
COUNT( p.user ) AS post_count
FROM users u
LEFT JOIN posts p ON u.user LIKE p.user
GROUP BY u.user_id;
... and performs an INNER JOIN with Users on shared value of user_id, creating a dataset with every row from users having the corresponding count tacked on the end.
We then use the SET command to set the empty post_count from users to its corresponding joined count.
If you have any questions or comments, thenplease feel free to post a Comment accordingly.
You need update statement to update the value in the newly added column.Try this:
Update usr
set usr.post_count=tbl.post_count
from users usr
inner join
(select u.user_id,COUNT(p.user)
AS post_count FROM users u
LEFT JOIN posts p ON u.user LIKE p.user GROUP BY u.user_id ) tbl
on tbl.user_id=usr.user_id

Count rows from one tables of users in another table

I want to create a query for project listings that would give the number of registered applications, excluding the ones for which the user does not exist.
In this case, considering user 10 does not exist, I should have the query results as folows:
RESULTS
+----+------------+--------------+
| id | project | applications |
+----+------------+--------------+
| 1 | MyProject1 | 3 |
| 2 | MyProject2 | 0 |
| 3 | MyProject3 | 0 |
+----+------------+--------------+
TABLES
Projects
+----+------------+
| id | name |
+----+------------+
| 1 | MyProject1 |
| 2 | MyProject2 |
| 3 | MyProject3 |
+----+------------+
applications
+----+------+------------+
| id | user | project_id |
+----+------+------------+
| 1 | 3 | 1 |
| 2 | 4 | 1 |
| 3 | 5 | 1 |
| 4 | 10 | 1 |
+----+------+------------+
users
+----+---------+
| id | Name |
+----+---------+
| 1 | Smith |
| 2 | John |
| 3 | Paul |
| 4 | Chris |
| 5 | Gabriel |
+----+---------+
The below query is not excluding the non-existing users:
SELECT `projects` . * , (
SELECT COUNT( * )
FROM `applications`
WHERE `applications`.`project_id` = `projects`.`id`
AND EXISTS (
SELECT `applications`.`id`
FROM `applications` , `users`,`project`
WHERE `application`.`user` = `users`.`id` AND `applications`.`project_id` = `project`.`id`
)
) AS `applications`
FROM `projects` ORDER BY `id` DESC LIMIT 30
I think you want left join and group by:
select p.id, p.name, count(u.id)
from projects p left join
applications a
on p.id = a.project_id left join
users u
on a.user_id = u.id
group by p.id, p.name;
However, you might want to think about fixing the data. It seems like there should be foreign key relationships between applications and projects and applications and users. The ability to have an invalid user means that there is no valid foreign key relationship to users.
Your query looks overly complicated. This should do:
select
id,
name as project,
(
select count(*)
from applications a
where a.project_id = p.id
and a.user in (select id from users)
) as applications
from projects p;
Based on previous solution
select p.id, p.name, count(u.id)
from projects p left join
applications a
on p.id = a.project_id left join
users u
on a.user = u.id
where u.id is not null
group by p.id, p.name;
When you do a left join, if the search value doesn't exists, it returns null. Then filtering by excluding null users, will give you the result.
Please find a sqlfiddle to illustrate it : http://www.sqlfiddle.com/#!9/cbfec6/3
But easiest solution would be
select p.id, p.name, count(u.id)
from projects p,applications a, users u
where a.user = u.id
and p.id = a.project_id
group by p.id, p.name;

Query to get reposts from people the user is following

I have a table posts where all the posts by users are stored, the structure of this table is as follows
| post_id | post_user | post_content | post_date |
the users table is as follows
| user_id | username | user_joined |
user relationship table is as follows
| follower | following | rel_date |
this is the query I am using to get the posts from people that user is following to show them.
SELECT * FROM posts WHERE post_user in(SELECT follower from user_follow where following=$loggedin_user)
Now I want users to share posts, for which I created a table repost_user as follows
| repost_user | original_post_user | post_id | repost_date |
I want to get posts from people that user following, which includes reposts too.. How do I do this?
EDIT : How my resultset should look
post_id | post_content | post_user | post_date | is_repost | repost_user | repost_date
for eg if its normal post the row should look like
23 | <some content> | 3 | <post date> | false | null | null |
if its a repost the rows would be
23 | <some content> | 3 | <post date> | true | 2 | <repost_date> |
Is that what You want ?
SELECT post_id,
post_content,
post_user,
post_date,
if(repost_user.post_id is null, 0,1) is_repost,
repost_user,
repost_date
FROM posts
LEFT join repost_user
on posts.post_id=repost_user.post_id
WHERE (repost_user in
(SELECT follower from user_follow where following=$loggedin_user)
or post_user in
(SELECT follower from user_follow where following=$loggedin_user) )
AND posts.post_id IS NOT NULL

MySQL Query Join to select unmatched rows from two tables

I have two tables as below.
user_id | username | first_name | role_type
-----------------------------------------------------------
1 | testuser1 | testu1 | student
2 | testuser2 | testu2 | student
3 | testuser3 | testu3 | student
4 | testuser4 | testu4 | student
5 | testuser5 | testu5 | student
6 | testuser6 | testu6 | admin
7 | testuser7 | testu7 | admin
-----------------------------------------------------------
user_id | username | approved_id
----------------------------------------------------------------------
1 | testuser1 | 3B888F52-50BC-11E2-B08B-99E5B2CADDF7
2 | testuser2 | 3B888F52-50BC-11E2-B08B-99E5B2CADDF7
3 | testuser3 | 3B888F52-50BC-11E2-B08B-99E5B2CADDF7
----------------------------------------------------------------------
I tried the query
SELECT users.* FROM users
WHERE users.username NOT IN(
SELECT users_approval.username FROM users_approval
WHERE users_approval.approved_id = "3B888F52-50BC-11E2-B08B-99E5B2CADDF7"
) AND users.role_type = "student"
and got the result below
user_id | username | first_name | role_type
-------------------------------------------------------------
4 | testuser4 | testu4 | student
5 | testuser5 | testu5 | student
-------------------------------------------------------------
Is there any way to use JOIN to fetch the same resultset as above ?.
Help is much appriciated.
SELECT users.*
FROM users
LEFT JOIN users_approval b
ON users.username = b.username AND
b.approved_id = "3B888F52-50BC-11E2-B08B-99E5B2CADDF7"
WHERE users.role_type = "student" AND
b.approved_id IS NULL
SQLFiddle Demo
SELECT
users.*
FROM users as u
LEFT JOIN users_approval as ua ON ua.id = u.id
WHERE u.role_type = "student" AND ua.approved_id IS NULL
Assuming you have user_id as foreign key in the second table it can be used to join instead of using username to join table