join 3 tables and select count - mysql

i have 3 tables {websites} {accounts} {ads}
websites table
id title url etc
-----------------------------------
1 site1 site1.com ...
2 site2 site1.com ...
3 site3 site3.com ...
accounts table
id websiteID username etc
-----------------------------------
1 1 username1 ...
2 2 username2 ...
3 1 username1 ...
4 3 username5 ...
ads table
id accountID title etc
---------------------------------
1 1 title1 ...
2 2 title1 ...
3 1 title3 ...
5 4 title4 ...
i want to join these 3 table start from website table and get some data from website table , and accounts_count ralated to its website , and ads_count related to its account . also i want zero or null result for counts.
usernames inside account table are not unique and can be same.
titles inside ads table are not unique too and can be same.
this is my query but some times it return wrong result on counts !
SELECT
websites.id as website_id
, websites.title as website_title
, COUNT(accounts.websiteID) as accounts_count
, COUNT(ads.accountID) as ads_count
, ads.lastUpdate
, websites.activation as website_activation
FROM websites
LEFT JOIN accounts
ON websites.id = accounts.websiteID
LEFT JOIN ads
ON accounts.id = ads.accountID
GROUP BY websites.id;
can u help me :{
i want show this result in a table like this:
website_title accounts_count ads_count last update operations
-------------------------------------------------------------------------
website1 3 8 2017/07/27 etc...
website2 0 0 2017/07/27 etc...
website3 3 9 2017/07/27 etc...
website4 5 15 2017/07/27 etc...

Seems that the counts need to change.
And a MAX for the ads.lastUpdate would be more accurate.
F.e.
SELECT
websites.id as website_id
, websites.title as website_title
, COUNT(DISTINCT accounts.ID) as accounts_count
, COUNT(ads.ID) as ads_count
, MAX(ads.lastUpdate) as LastUpdateAds
, websites.activation as website_activation
FROM websites
LEFT JOIN accounts
ON websites.id = accounts.websiteID
LEFT JOIN ads
ON accounts.id = ads.accountID
GROUP BY websites.id;

The thing is when you join websites with accounts you get row for each row in accounts. Then when you join with ads you further multiplicate the row count. My guess is you now get same count for accounts_count and ads_count. Furthermore you have lastUpdate column from ads table and with agregate function.

SELECT websites.id as website_id, websites.title as website_title,
ads.lastUpdate, websites.activation as website_activation
COUNT(accounts.websiteID) as accounts_count, COUNT(ads.accountID) as ads_count,
FROM websites, accounts, ads
WHERE websites.id = accounts.websiteID
AND accounts.id = ads.accountID;

Related

Left Join and remove duplicates

I have three tables, clients, job_allocations and jobs table. I want to select all clients that are not in a particular job, below are my tables.
Clients table
id
Fullname
1
John Doe
2
Jane Doe
3
King James
4
Jere Gray
Jobs table
id
Title
1
Road Construction
2
Repair of Engines
job_allocations table
id
client_id
job_id
1
2
1
2
2
2
3
1
2
4
3
2
I want to select all clients that are not in job_id=2, but when I ran my query, I am getting client id: 2 - Jane Doe again, please how do I solve this?
I did this:
LEFT JOIN job_allocations ON job_allocations.client_id = clients.id
WHERE job_id <> 2 OR job_id IS NULL```
You can use a NOT IN clause as follows:
SELECT *
FROM clients
WHERE id NOT IN (SELECT client_id
FROM job_allocations
WHERE job_id = 2)
Check the demo here.
So you will fetch all clients, but only jobs related to job_id <> 2
This query should work for you:
SELECT client.*
FROM clients
LEFT JOIN job_allocations ON job_allocations.client_id = clients.id and job_id <> 2
Use DISTINCT keyword for selecting unique values

MySQL: Add multiple columns after GROUP BY?

I am trying to do following:
SELECT
customer_entity.email,
customer_entity.website_id
FROM
customer_entity
INNER JOIN
(SELECT
email
FROM
customer_entity
GROUP BY email
HAVING COUNT(email) > 1) dupes
ON customer_entity.email = dupes.email
GROUP BY customer_entity.`entity_id`
ORDER BY customer_entity.email ;
Above query returns the result below:
email website_id
abe#abc.com 1
abe#abc.com 2
abe#abc.com 3
abe#abc.com 4
test#abc.com 1
test#abc.com 2
test#abc.com 4
xyz#abc.tv 1
xyz#abc.tv 2
xyz#abc.tv 3
But I want data in below format:
email website1 website2 website3 website4
abe#abc.com 1 2 3 4
test#abc.com 1 2 null 4
xyz#abc.tv 1 2 3 null
is it possible in this case?
Thanks
You can do conditional aggregation:
select
email,
max(website_id = 1) website_1,
max(website_id = 2) website_2,
max(website_id = 3) website_3,
max(website_id = 4) website_4
from customer_entity
group by email
having count(*) > 1
order by email
Note that this simplifies your original query - a self-join is not needed here.
Also, this puts 0/1 values in each column that indicates whether the given email exists for this website - I find that it is more meaningful than repeating the website id in the column.

How to Join 3 MYSQL Tables with multiple conditions and even if no data in 3rd table

My New Project is something like a blog roll in which users can follow other users.
While listing all Posts, There will be a button to follow/unfollow under each post.
Tables used are users, posts and followers. which are as follows:
USER Table
id firstName lastName
.....................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 John abc
POSTS Table
id user_id postname url
.....................................................
1 2 post1 www.url1.com
2 2 post2 www.url2.com
3 6 post3 www.url3.com
4 3 post4 www.url4.com
Followers Table
id user_id following_users_id date
..............................................
1 2 1 2018-01-25
2 2 3 2018-01-25
3 6 3 2018-01-25
4 3 6 2018-01-25
to list all posts my query was like:
SELECT * FROM posts LEFT JOIN users on posts.user_id = users.user_id;
and it worked fine as both table have corresponding rows and the result was by listing both table columns with all data.
Now My issue is while joining third table, ie followers table. problem with followers table is, it will have only one row which corresponds to current logged in users user_id and followers.user_id.
i tried all variants like LEFT RIGHT INNER and OUTER JOIN's. but no success.
the result i want is:
user.id -> xxx
user.firstName -> xxx
user.lastName -> xxx
posts.id -> xxx
posts.user_id -> xxx
posts.postname -> xxx
posts.url -> xxx
followers.id -> xxx
followers.user_id -> **Logged IN Users ID**
followers.following_users_id -> **posts.user_id**
followers.date -> xxx
the followers.id, followers.user_id, followers.following_users_id, followers.date should be printed only if followers.user_id === Logged IN Users ID AND followers.following_users_id === posts.user_id is true. else those columns should be blank.
Is there any way i can retrieve data as mentioned above of should i use something like a foreach loop?

Mysql join query with where and like

I have three related tables users, groups and group_members. The users table contains users information and groups table contains the group name and group owner id (ie, users_id). Table group_members contains the members of each groups (user_id and group_id). I tried to load the users details of each group but the result is not correct. My tables are,
users
id firstname lastname email
1 anu mm anu#gmail.com
2 manu mohan manu#gmail.com
3 cinu ab cinu#gmail.com
4 vinu mj vinu#gmail.com
5 vijesh cc vijesh#gmail.com
6 admin admin admin#gmail.com
groups
id user_id name
1 1 group1
2 2 group2
3 2 group3
4 3 group4
group_members
id user_id group_id
1 1 1
2 2 2
3 2 3
4 3 4
5 2 3
7 1 2
8 1 3
9 3 1
But when I tried the bellow query,
select users.firstname,users.lastname,users.email,groups.name as groupname from users inner join groups on groups.user_id = users.id inner join group_members on group_members.group_id = groups.id where groups.id=3 AND users.firstname LIKE 'cin%' OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%'
getting the result (which is not expected)
firstname lastname email groupname
cinu ab cinu#gmail.com group4
In this case I used the where condition WHERE groups.id =3 but the result takes the group4 (groups.id is 4). Please suggest me a solution.
your have to use () arround your or statements:
where groups.id=3 AND (users.firstname LIKE 'cin%' OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%')
Because AND has a higher priority you query looks like:
where (groups.id=3 AND users.firstname LIKE 'cin%') OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%'
And that is not what you want.

How to make my mysql queries for showing friends feeds?

Here is my table structure.(fun_friends)
id user_id,friend_id,status,createdat,updatedat
1 1 2 1 123456 125461
2 1 3 1 454545 448788
3 2 4 1 565659 898889
4 1 5 1 877878 878788
Here is the table structure of user_uploads
id user_id parent_id category_id title slug tags description video_type source video_link video_thumb
1 2 1 2 fun fun ['4','5'] coolvid 1 ytu link thumb
I need to show the latest upload of my friends
Can you tell me how can i join this tables together? i tried with
SELECT * FROM fun_friends WHERE (user_id= '".$_SESSION['user_row_id']."' AND `status` =1) OR (friend_id= '".$_SESSION['user_row_id']."' AND `status` =1)
and it is showing all friends of logged-in user
You can just join both table using user_id field. sample query bellow will return one record with latest user_uploads.id.
select *
from fun_friends a
inner join user_uploads b on a.user_id = b.user id
order by b.id desc limit 0,1
how about using UNION to get the friends user and wrapping it inside a subquery which later join on the other tabel,
SELECT usr.*
FROM user_uploads usr
INNER JOIN
(
SELECT user_ID AS ID
FROM Fun_Friends
WHERE friend_ID = 'ID_HERE'
UNION
SELECT friend_ID As ID
FROM Fun_Friends
WHERE ser_ID = 'ID_HERE'
) idList ON usr.user_ID = idList.ID