How do I perform a simple join on multiple tables? - mysql

I have what I'm sure is quite a remedial question here, but I can't for the life of me get this simple join to work.
Basically, I have 3 tables:
MEMBERS (first_name,last_name),
MEMBER_TO_GROUP(member_id,group_id)
PAYMENTS (member_id, date, amount).
I'm looking to grab all payments from members in a specific group. By using only two of the tables, I can find all PAYMENTS of a specific group, without MEMBER information, or I can find all MEMBER information without PAYMENT information. However, when I attempt to add the third table, bad data is returned (e.g. I get members not in the group). This is the basic query i'm using:
SELECT
p.*,
m.first_name,
m.last_name
FROM
members m,
payments p,
member_to_group mg
WHERE
mg.group_id = 12
AND mg.member_id = p.member_id
AND m.member_id = p.member_id
I'm not sure where the disconnect is, but any assistance would be most appreciated.

I think this should get what you want:
SELECT p.*,
m.first_name,
m.last_name
FROM payments p
INNER JOIN members m
ON m.member_id = p.member_id
INNER JOIN member_to_group mg
ON mg.member_id = m.member_id
WHERE mg.group_id = 12

Related

to get different columns from single query

Consider the data about projects and members stored in tables below.

Projects(id, title)
Members(id, name, project_id)

Generate a report to list all the projects, members working on them. Also list the projects that do not have any employees assigned yet and also the employees who are available as free resources.
Table-
Projects(id, title)
Members(id, name, project_id)
can someone optimize the query as i applied outer join and i got all answers together.i need to separate the columns as per required question.
Select p.title, m.id
From projects p FULL OUTER JOIN
Members m
where p.id = m.project_id;
MySQL does not support full join. So do this in two steps:
Select p.title, m.id
From projects p LEFT JOIN
Members m
ON p.id = m.project_id
union all
select null, m.id
from members m
where not exists (select 1 from projects p where p.id = m.project_id);

Struggling with correlated subqueries in SQL

I have a database about old cars, their owners, events and the attendants of those events as such:
Image of tables used :
PK: Primary Key
FK: Foreign Key
Now I need to get the amount of different events (eventId) each member (memberId) has attended.
Important note: a member can have multiple cars that can each attend events.
Here is one of my attemps:
select m.memberId, count(a.eventId).
from members m where m.memberId in (select c.memberId from cars c where m.memberId =
c.memberId and c.carId in
(select d.carId from attendants a where c.carId = d.carId))
order by m.memberId
I've also tried using joins and group by to get a correct result but I am getting nowhere.
Does anyone know how i need to form the subquery so that i can get the results needed?
So you want distinct events the member has attended. Member has cars which attend the events. Since different cars can attend same events, you need to take distinct from events:
select m.memberId, count(distinct a.eventId)
from members m
join cars c on c.memberId = m.memberId
join attendants a on a.carId = c.carId
group by m.memberId
Not sure if you are using that exact statement, but your syntax has several issues. You're using aliases that don't exist (d.CarID - what table is d?) and you don't have a group by statement at the end, which tells the engine what columns you want to preserve the values from. Try something like this:
select member_ID,
count(*)
from (
select distinct a.eventID, m.memberID
from attendants a
inner join cars c
on a.carID = c.car_ID
inner join members m
on c.memberID = m.memberID
group by a.eventID, m.memberID
)
group by memberID
The inner query gets what you want - a big list of all the members who have attended via the cars they own, deduped so that if they had two cars at the same event they are only recorded once - which is then counted for each member.

3 table query with count

I'm having huge difficulty with a 3 table query.
The scenario is that TEAM has many or no MEMBERS, a MEMBER could have many or no TASKS. What I want to get is the number of TASKS for every TEAM. TEAM has its own ID, MEMBER holds this as a FK on TEAM_ID, TASK has MEMBER_ID on the TASK.
I want to get a report of TEAM.NAME, COUNT(Person/Team), Count(Tasks/Team)
I have myself so confused, My thinking was to use an Outer Join on TEAM and MEMBER so I have all the teams with any members they have. From here I'm getting totally confused. If anyone can just point me in the right direction so I have something to work from I'd be so greateful
You want to use count distinct:
MySQL COUNT DISTINCT
select t.name as Team,
count(distinct m.ID) as Member_cnt,
count(distinct t.ID) as Task_cnt
from team t
left join member m
on t.ID= m.TEAM_ID
left join tasks t
on t.MEMBER_ID= m.ID
group by t.name;
I think you can do what you want with aggregation -- and count(distinct):
select t.name,
count(distinct m.memberid) as nummembers,
count(distinct tk.taskid) as numtasks
from team t left join
member m
on t.teamid = j.teamid left join
tasks tk
on tk.memberid = m.memberid
group by t.name;
Try this out :
SELECT Team.name, COUNT(Person.id_person), COUNT(Tasks.id_task)
FROM Team t,
LEFT JOIN Person p on p.team_id = t.id_team
LEFT JOIN Tasks ts on ts.person_id = p.id_person
GROUP BY p.team_id, ts.person_id

MySQL Subquery returns more than 1 row on 3 tables

SELECT b.bill_no, b.case_no, b.patient_id,
(Select (lastname) from myhospital.patient p where p.patient_id = b.patient_id) as l_name,
(Select (givenname) from myhospital.patient p where p.patient_id = b.patient_id) as f_name,
(Select (middle) from myhospital.patient p where p.patient_id = b.patient_id) as m_name,
(select (address_street) from myhospital.patient p where
p.patient_id = b.patient_id) as adress, m. item_name,
(select cast(m.unit_price as Char(8))) as unit_price,
(select cast(m.qty as Char(8))) as quantity,
(select cast(m.charges as Char(8))) as charges,
m.date_rec, m.service_code,
(select (descript) from myhospital.hosp_services s where m.service_code = s.service_code) as Section,
(Select (fullname) from myhospital.users u where u.user_id = m.edit_by) as Encode_by,
(Select (descript) from myhospital.hosp_bill_etc c where b.bill_no = c.bill_no) as misc_edit
FROM myhospital.hosp_bill b join myhospital.hosp_bill_meds m
where b.bill_no = m.bill_no
I have join 2 tables from 1 database and i want to add another table which is "myhospital.hosp_bill_etc" and i am getting an error
subquery returns more than 1 row,
please someone tell me how to solve this.
As you stated, you are obviously new to querying, and it does take practice. Start by learning the relationships between the tables, and to direct joins (or left joins) without doing repeated queries. So, the patient information should be a single record for the given "patient_id". The joins between tables needs to identify HOW they are related or you will get Cartesian results. Notice how I am showing the relationship between respective tables via the "ON" command. And for readability, notice how I am visually nesting the table relations such as from billing to bill meds to hosp services, and users etc.
Now, you can get any column from the respective table(s) in the field selection list by the simple alias... Anyhow, hopefully a little help for you... Also, I don't know why you are casting the charges, qty, price as character. Typically output to what ever would formatted there and leave original value(s) as-is.
SELECT
b.bill_no,
b.case_no,
b.patient_id,
p.lastname as l_name,
p.givenname as f_name,
p.middle as m_name,
p.address_street as address,
m. item_name,
m.unit_price,
m.qty as quantity,
m.charges,
m.date_rec,
m.service_code,
s.descript as Section,
u.fullname as Encode_by,
c.descript as misc_edit
FROM
myhospital.hosp_bill b
JOIN myhospital.patient p
ON b.patient_id = p.patient_id
JOIN myhospital.hosp_bill_meds m
ON b.bill_no = m.bill_no
JOIN myhospital.hosp_services s
ON m.service_code = s.service_code
JOIN myhospital.users u
ON m.edit_by = u.user_id
JOIN myhospital.hosp_bill_etc c
ON b.bill_no = c.bill_no
So this is the relationships for the tables, but it will now return ALL entries for ALL patients. If you want something for a specific bill, or patient, you would add a WHERE clause for that specific component.
Now, it appears a bill is always to a single patient.
A bill has many meds.
Each med I would think has a single service, but if one med can have more than one, you will get duplicates.
Also, for each med, I would expect a single person associated with who recorded/distributed the meds.
Finally your "bill_etc". If this has multiple rows, that too could cause a Cartesian result.
Hopefully a good start based on YOUR data environment vs so many generics that you might have to wrap your head around, but PLEASE do some more reading on SQL practices.

Need to use criteria from multiple tables to acquire data from multiple tables

I'm having a bit of a hiccup regarding a particular SQL query. I need to join data from two tables, while also limiting the data (but not necessarily grabbing it) by means of a third table. The tables are as follows:
MEMBERS(member_id,first_name,last_name)
MEMBERS_GROUPS(member_id,group_id)
CHARGES(charge_id,member_id,charge_amount,status)
I need to find all charges for all members of a specific group but I also want to grab the first and last name from the MEMBERS table. The query I've come up with thus far is:
select c.*, m.first_name, m.last_name
FROM charges c
LEFT JOIN member m
ON c.member_id=m.member_id
INNER JOIN members_groups mg
ON mg.group_id=1
i've also tried:
SELECT c.*, m.first_name, m.last_name
FROM charges c, members_groups mg, member m
WHERE c.member_id=mg.member_id
AND mg.group_id = 1
AND c.status='Valid'
AND c.member_id = m.member_id
…but neither returns the data I need. I'm sure I'm overthinking this, but I can't for the life of me get the correct values. I keep getting what appears to be the Cartesian product -- regardless, it's clearly returning too many rows and bad data.
Perhaps what you need is to also restrict the INNER JOIN on members_groups to
those rows with mg.member_id = m.member_id:
SELECT c.*, m.first_name, m.last_name
FROM charges c
LEFT JOIN member m
ON c.member_id=m.member_id
INNER JOIN members_groups mg
ON mg.group_id=1
AND mg.member_id = m.member_id