3 table left outer join doesn't work with subquery - php

A brief description... I have 4 tables. "contacts" (a list of each person, unique IDs), contact_phones (multiple telephone numbers for each contact, joins on contact_id), and contact_communication (each time we've spoken to this contact, joins on contact_id), and schools (a list of schools, joins schools.school_id = contacts.contact_id).
What I need: I need to look up an individual school. For that school, I need a list of each person that goes there, their main telephone number, and the last communication we had with them (if any).
The problem is, if we have had NO communication with them, they don't show up in the list. If I take out the "AND" statement in the "WHERE" clause, then I get more than one communication record. I only want the latest communication record, but I want all the contacts. Some contacts don't have a communication record though.
This is my query:
SELECT c.id,
c.f_name,
c.l_name,
c.address1,
c.address2,
c.city,
c.state,
c.zip,
c.tel,
c.school_id,
c.email,
ct.tel,
cc.date,
cc.reason,
cc.result,
cc.caller
FROM contacts AS c
LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id
WHERE school_id = '$schoolId' AND
cc.id IN (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id)
ORDER BY cc.date DESC
The problem is, this query gives me only the latest communication (which is all I want) but won't list contacts that have no communication.
I've been at this for 3 days. Any tips?
Thanks!!
(PS: I'll edit and give more info if needed.)
EDIT
The answer (thank you, ysrb) is changing my where clause:
SELECT c.id,
c.f_name,
c.l_name,
c.address1,
c.address2,
c.city,
c.state,
c.zip,
c.tel,
c.school_id,
c.email,
ct.tel,
cc.date,
cc.reason,
cc.result,
cc.caller
FROM contacts AS c
LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id
WHERE school_id = '$schoolId' AND
(cc.id IN (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id) OR cc.id IS NULL)
ORDER BY cc.date DESC

Try:
SELECT c.id,
c.f_name,
c.l_name,
c.address1,
c.address2,
c.city,
c.state,
c.zip,
c.tel,
c.school_id,
c.email,
ct.tel,
cc.date,
cc.reason,
cc.result,
cc.caller
FROM contacts AS c
LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id
WHERE school_id = '$schoolId' AND
(cc.id = (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id) OR cc.ID IS NULL)
ORDER BY cc.date DESC

Related

How to show name of course in INNER JOIN?

I have two tables: users and courses. Inside users table i have filed course where i have course id. Inside courses table i have just ID and NAME.
I need to get popular course. I do request:
SELECT u.course, COUNT(*) as freq FROM users u INNER JOIN courses c ON u.course = c.id GROUP BY u.course
As a result: id => freq. But i need to replace ID to NAME of course. How?
Thanks.
You don't say what database you use, but I would assume you can use CTEs since most modern databases do. Your query can be written as:
with x as (
select course, count(*) as freq from users group by course
),
y as (
select max(freq) as max_freq from x
)
select c.name, x.freq
from x
join y on x.freq = y.max_freq
join courses c on c.id = x.course
This query has the [desirable?] side effect that it shows more than one course, if there are more than one tied in first place.
Add c.name to both the SELECT clause and the GROUP BY clause.
SELECT u.course, c.name, COUNT(*) as freq
FROM users u
INNER JOIN courses c
ON u.course = c.id
GROUP BY u.course, c.name;
Demo: https://dbfiddle.uk/?rdbms=mariadb_10.3&fiddle=02a41e0f1e6407e516e91c49b4bdc1d2
SELECT u.course, COUNT(*) as freq, c.name FROM users u INNER JOIN courses c ON u.course = c.id GROUP BY u.course
If your DBMS supports row_number this will be suitable:
select t.id, c.name, t.cnt
from course c
join (
select c.id, count(1) cnt, ROW_NUMBER() over(order by count(1) desc) rn
from users u
join course c on c.id = u.course
group by id
)t on t.id = c.id and t.rn = 1

mySQl, Query: How to customize selection from database?

I have four tables:
courses, allocate_rooms, rooms, departments
Query:
SELECT
courses.`name`,
courses.`code`,
allocate_rooms.`start`,
allocate_rooms.`end`,
rooms.room_number
FROM
departments
JOIN courses ON departments.id = courses.department_id
LEFT JOIN allocate_rooms ON allocate_rooms.course_id = courses.id
LEFT JOIN rooms ON allocate_rooms.room_id = rooms.id
WHERE
departments.id = 1
From the Query I have to make a selection view as rooms.room_number, allocate_rooms.start-allocate.rooms_end; and if there is no data related to that course I have to show "Not Scheduled Yet".
Eg: R.No: 301,12:00-12:30; (if the course related data is there otherwise it will show "Not Scheduled Yet"
How do I rewrite the above Query? If anybody help me to find the solution.
I'm not sure if it's what you need, but try this:
You can use DECODE for getting what you need.
SELECT
c.name name
,c.code code
,decode(ar.start,NULL,'Not Schedule Yet') START
,decode(ar.end,NULL,'Not Schedule Yet') END
,r.room_number roomnum
FROM
departments d
,courses c
,allocate_rooms ar
,rooms r
WHEREd.id = c.id
AND ar.course_id = c.id
AND ar.room_id = r.room_id
AND d.id = 1;
You can try with ifnull
SELECT courses.name, courses.code, allocate_rooms.start,
allocate_rooms.end ,
case rooms.room_number
WHEN IS NULL THEN 'No Rooms allocated'
WHEN 0 THEN 'No Rooms allocated'
ELSE room.room_number
end
FROM departments
join courses on departments.id = courses.department_id
left join allocate_rooms on allocate_rooms.course_id=courses.id
left join rooms on allocate_rooms.room_id=rooms.id
WHERE departments.id=1
Here is the solution:
SELECT courses.name, courses.code,COALESCE( CONCAT('R. No',':',rooms.room_number,', ',days.name ,', ', allocate_rooms.start,' - ',allocate_rooms.end),"Not Assigned Yet") AS Schedule
FROM departments join courses on departments.id = courses.department_id
left join allocate_rooms on allocate_rooms.course_id=courses.id
left join rooms on allocate_rooms.room_id=rooms.id
left join days on allocate_rooms.day_id=days.id WHERE departments.id=1

Resolve data for 2 tables

Let's say, I have 3 tables. "users", "topics" and "replies.
The "topics" and "replies" table do have a column "user_id" which references to "id" on the "users" table. The "replies" table also have a column "topic_id" which references "id" on "topics". Also imagine that each topic has 1 reply.
Now, I want to fetch all topics and resolve the username for both tables, so the output should include a "topic_username" and a "reply_username".
I know how to select the username for the topic, but how can I do that for both the topics and replies table?
Thanks
Updated code:
SELECT
t.*,
t_users.username as topic_user,
last_reply.user_id as last_reply_user_id,
r_users.username as last_reply_username,
last_reply.replies_count,
ORDER BY IFNULL(last_reply.created_at,t.created_at DESC
FROM
topics as t
left join users as t_users on t_users.id = t.user_id
left join ( select r.*,count(r.id) as replies_count from (select * from replies order by id desc) as r group by r.topic_id ) as last_reply on last_reply.topic_id = t.id
left join users as r_users on r_users.id = last_reply.user_id
Try this
SELECT
t.*,
t_users.name as topic_user,
r_users.name as reply_user
FROM
topics as t
left join replies as r on r.topic_id=t.id
left join users as t_users on t_users.id = t.user_id
left join users as r_users on r_users.id = r.user_id
this would work well if there is 1:1 topic and reply, if you have 1 to many replies then you are better off group by topic id and get the usernames by group concat
Version 2 (to get reply count and last reply user)
SELECT
t.*,
t_users.name as topic_user,
last_reply.user_id as last_reply_user_id,
r_users.name as last_reply_username,
last_reply.replies_count,
IFNULL(last_reply.created_at,t.created_at) as last_update
FROM
topics as t
left join users as t_users on t_users.id = t.user_id
left join ( select r.*,count(r.id) as replies_count from (select * from replies order by id desc) as r group by r.topic_id ) as last_reply on last_reply.topic_id = t.id
left join users as r_users on r_users.id = last_reply.user_id
ORDER BY IFNULL(last_reply.created_at,t.created_at) DESC
You wanna do this in a single query? You can do it like this but I believe a separate query for fetching replies and topics might be better (fetch replies first, get the unique topic IDs and then fetch topics in a separate query)
SELECT r.id, r.topic_id, ru.username AS reply_username, tu.username AS topic_username
FROM replies AS r
INNER JOIN topics AS t ON (t.id = r.topic_id)
INNER JOIN users AS ru ON (r.user_id = u.id)
INNER JOIN users AS tu ON (t.user_id = u.id)

MySQL - Having problems with COUNT() in query with GROUP BY

I have a pretty big query which is used by an ajax call to return and also sort active items. From my understanding sub queries should be avoided where possible and since this query will be called very often, I would like to do just that.
At the moment everything is fine except for the COUNT(b.bic) AS bids. If there are two(2) bids the query returns four(4), if there are 4, it returns 8, and so on. I've tried grouping by other columns ... but no luck.
Some of the tables. I hope each of the column names are pretty self explanatory:
countries_ship - each item can be shipped to multiple countries so item_id can be duplicate.
id item_id country_id ship_cost
countries
id country_code country_name
item_expire - not sure if item_expire should have it's own table.
id item_id exp_date
bids - Just as countries_ship, item_id can be duplicate. This is where the bids are stored.
id item_id user_id bid previous_bid bid_date
The query:
$q = $this->db->mysqli->prepare("
SELECT c.ship_cost,
c.item_id,
co.country_name,
co.id AS co_id,
i.id,
i.user_id,
i.item_start,
i.item_title,
i.item_number,
i.item_year,
i.item_publisher,
i.item_condition,
i.item_description,
i.item_location,
e.exp_date AS exp_date,
i.active,
CAST(u.fb_id AS CHAR(50)) AS fb_id,
u.user_pic,
MAX(b.bid) AS maxbid,
COUNT(b.bid) AS bids,
p.publisher_name,
t.tag_name
FROM countries_ship c
JOIN items i
ON c.item_id = i.id
JOIN item_expire e
ON c.item_id = e.item_id
JOIN users u
ON i.user_id = u.id
LEFT JOIN bids b
ON i.id = b.item_id
LEFT JOIN publishers p
ON i.item_publisher = p.id
LEFT JOIN tags_rel tr
ON c.item_id = tr.item_id
JOIN tags t
ON t.id = tr.tag_id
LEFT JOIN countries co
ON i.item_location = co.id
WHERE ".$where."
GROUP BY c.item_id ORDER BY ".$order." ".$limit."");
You may try
COUNT(distinct b.bic) AS bids
This will ignore duplicates due to joins

mysql join return 0 for one column with other columns intact

I wish to join multiple tables like- Categories, menus, restaurants, reviews, etc.
to return the restaurants that provide the inserted food with their prices.
Everything works except numberOfReviews in reviews table.
If a restaurant has no reviews then output should be 0 for numOfReviews column but other column values should be retrieved i.e. price, name, etc.
With following query I get all fields as null and count(numReviews) as 0:
select r.id
,r.`Name`
,r.`Address`
,r.city
,r.`Rating`
,r.`Latitude`
,a.`AreaName`
,m.`Price`
,count(rv.id)
from `categories` c, `menus` m, `restaurants` r, areas a, reviews rv
where m.`ItemName`="tiramisu"
and c.`restaurant_id`=r.`id`
and m.`category_id`=c.id
and r.`AreaId`=a.`AreaId`
and if I can't match rv.restaurant_id=r.id in where clause(obviously).
Where am I getting wrong? How do I solve this?
edited
select r.id,
r.`Name`,
r.`Address`,
r.city,
r.`Rating`,
r.`Latitude`,
a.`AreaName`,
m.`Price`,
r.`Longitude`,
r.Veg_NonVeg,
count(rv.id)
from restaurants r LEFT JOIN `reviews` rv on rv.`restaurant_id`=r.`id`
inner join `categories` c on c.`restaurant_id` = r.id
inner join `menus` m on m.`category_id` = c.id
inner join `areas` a on a.`AreaId` = r.`AreaId`
where m.`ItemName`="tiramisu"
First of all, don't use this old school syntax for the jointures.
Here is a query that may solve your problem:
SELECT R.id
,R.Name
,R.Address
,R.city
,R.Rating
,R.Latitude
,R.Longitude
,A.AreaName
,M.Price
,R.Veg_NonVeg
,COUNT(RV.id) AS numOfReviews
FROM restaurants R
INNER JOIN categories C ON C.restaurant_id = R.id
INNER JOIN menus M ON M.category_id = C.id
INNER JOIN areas A ON A.AreaId = R.AreaId
LEFT JOIN reviews RV ON RV.restaurant_id = R.id
WHERE M.ItemName = 'tiramisu'
GROUP BY R.id, R.Name, R.Address, R.city, R.Rating, R.Latitude, R.Longitude, A.AreaName, M.Price, R.Veg_NonVeg
I used explicit INNER JOIN syntax instead of your old school syntax and I modified the jointure with table reviews in order to get the expected result. The GROUP BY clause is required to use the aggregate function COUNT, every rows will be grouped by the enumerated columns (every column except the one used by the function).
Here is another solution that simplify the GROUP BY clause and allow the modification of SELECT statement without having to worry about the fact that every columns need to be part of the GROUP BY clause:
SELECT R.id
,R.Name
,R.Address
,R.city
,R.Rating
,R.Latitude
,R.Longitude
,A.AreaName
,M.Price
,R.Veg_NonVeg
,NR.numOfReviews
FROM restaurants R
INNER JOIN (SELECT R2.id
,COUNT(RV.id) AS numOfReviews
FROM restaurants R2
LEFT OUTER JOIN reviews RV ON RV.restaurant_id = R2.id
GROUP BY R2.id) NR ON NR.id = R.id
INNER JOIN categories C ON C.restaurant_id = R.id
INNER JOIN menus M ON M.category_id = C.id
INNER JOIN areas A ON A.AreaId = R.AreaId
WHERE M.ItemName = 'tiramisu'
As you can see here I added a new jointure on a simple subquery that does the aggregation job in order to provide me the expected number of reviews for each restaurant.
Hope this will help you.

Categories