How to relate a table more than one time in SQL? - mysql

I want to relate two tables and a relation table. Tables are: Person with it's primary key named id_person, Activity with it's primary key named id_activity and a table that relates the previous two tables: Activity_Person that contain as primary and foreign keys id_activity and id_person.
To relate this tables using the old JOIN format this would work:
select * from activity, person, activity_person
where activity.id_activity = activity_person.id_activity and person.id_person = activity_person.id_person;
This would show the activities that each person has taken part on.
But now I'm learning about JOINs and I don't know what's the correct format to relate a table that appears twice (Activity_Person).
I have tried this:
select * from
person inner join activity_person on person.id_person = activity_person.id_person,
activity inner join activity_person on activity.id_activity = activity_person.id_activity;
But I get the following error:
Not unique table/alias: 'activity_person'
What's the correct format?

You don't need activity_person twice here. Just do
select *
from person
inner join activity_person on person.id_person = activity_person.id_person
inner join activity on activity.id_activity = activity_person.id_activity;

I think you just want two joins:
select *
from person p inner join
activity_person ap
on p.id_person = ap.id_person inner join
activity a
on a.id_activity = ap.id_activity;
I'm not sure why you are trying to repeat activity_person in your query.
Also note that table aliases make the query easier to write and to read.

Your syntax is incorrect.
select * from activity, person, activity_person
where activity.id_activity = activity_person.id_activity
and person.id_person = activity_person.id_person;
Is equivalent to :
select *
from person
inner join activity_person
on person.id_person = activity_person.id_person -- <- remove the comma there
inner join activity
on activity.id_activity = activity_person.id_activity;
Basically, the syntax is like this :
SELECT <the fields to select>
FROM <table name>
JOIN <table to join>
ON <joining condition>
-- if you want to add another table :
JOIN <new table to join>
ON <joining condition>

Related

Mysql query to join two tables using many to many relation

I have three tables called Notes another table called Tags and third as a Join table called NoteTagsJoin, Join table holds two foreign keys primary Note id and Primary Tag id. I use this query to get all Notes with tagId:
SELECT * FROM notes INNER JOIN note_tag_join ON notes.entryId = note_tag_join.noteId WHERE note_tag_join.tagId =:tagId
And this query to get all Tags:
SELECT * FROM tags INNER JOIN note_tag_join ON tags.tagId = note_tag_join.tagId WHERE note_tag_join.noteId =:noteId
How can I get Note and all its tags using just Note id with one query?
Are you looking for two joins?
SELECT n.*, t.*
FROM notes n INNER JOIN
note_tag_join nt
ON n.entryId = nt.noteId INNER JOIN
tag t
ON t.tagId = nt.tagId
WHERE n..entryId = :noteId
SELECT * FROM table_name
LEFT JOIN table_name2 ON table_name.id = table_name2.id
LEFT JOIN table_name3 ON table_name2.id = table_name3.id
WHERE table_name.id = id;
Change the "id" with the appropriate id's that you're using. It's important that the id's in the JOINs are coherent, else there will be no link between them.
If you want to select fields of the 3 tables, do this:
SELECT (fields that you want to show) FROM tableA
INNER JOIN tableB ON tableA.commonField = tableB.commonField
INNER JOIN tableC ON tableB.commonField = tableC.commonField

How to join datas from many different tables in mysql

I have a very difficult task for me. I don't understand, which query I should write to display needed dates.
So, the task is to join different tables in one temporary table.
I have tables
my database
So I want to get the patient's full name, his address, dob (date of birthday), his gender, user's full name, status's name and diagnosis
How to do it? Can you attach the link with the theory ?
Here's an Example:
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name
....
)
About Inner Join: Link
Creating a Temporary Table :Link
I assume dob and gender refer to patient dob and gender.
SELECT task.ID, task.diagnosis, patient.name, patient.surname, patient.m_name, user.name, user.surname, user.m_name, status.name, patient.address, patient.dob, patient.gender
FROM task
INNER JOIN user ON task.id_user=user.ID
INNER JOIN patient ON task.id_patient = patient.ID
INNER JOIN status ON task.id_status = status.ID
Here is an example how to use INNER JOIN.
You can read more here: JOIN Syntax

How to match this using SQL?

I am using the 3 following tables:
First table
id
response
Second table
responseid
patientid
Third table
patientid
The relationship between first and second table is on id and responceid.
The relationship between third and second is on patientid.
Now I need to retrieve values from these tables like all values from first and third tables with the help of matching with patientid from second and 3rd table.
How can I do this?
Basically if all of the columns that defines their relationship are not nullable, then INNER JOIN will suffice. But if they are nullable and you still want to display all records from firstTB, you need to use LEFT JOIN instead of INNER JOIN.
SELECT a.*, b.*, c.*
FROM firstTB a
INNER JOIN secondTB b
ON a.ID = b.responceID
INNER JOIN thirdTB c
ON b.patientID = c.patientID
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
You're probably looking for INNER JOIN or JOIN in general:
SELECT
response.id,
response.responce,
patient.patientid
FROM
`response_table` as `response`
INNER JOIN
`relation_table` as `relation`
ON
relation.responceid = response.id
INNER JOIN
`patient_table` as `patient`
ON
relation.patientid = patient.patientid
try
SELECT first.*
, third.*
FROM first
INNER JOIN second ON ( second.responseid = first.id )
INNER JOIN third ON ( third.patientid = second.patientid )
;
honestly, and no insult intended, if you have difficulties in coming up with queries like this one on your own, consider some training on db basics and db development, the sooner the better (just hoping i haven't blundered myself ... ;-)).

MySQL Multiple Joins in one query?

I have the following query:
SELECT
dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
So I am using an INNER JOIN and grabbing the image_id. So now, I want to take that image_id and turn it into images.filename from the images table.
How can I add that in to my query?
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
I shared my experience of using two LEFT JOINS in a single SQL query.
I have 3 tables:
Table 1) Patient consists columns PatientID, PatientName
Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID
Table 3) Doctor consists columns DoctorID, DoctorName
Query:
SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname
FROM Appointment
LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId //have doctorId column common
LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId //have patientid column common
WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE
AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates
ORDER BY AppointmentDateTime ASC; // getting data as ascending order
I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")
Multi joins in SQL work by progressively creating derived tables one after the other.
See this link explaining the process:
https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/

How do you do a mysql join where the join may come from one or another table

This is the query that I am using to match up a members name to an id.
SELECT eve_member_list.`characterID` ,eve_member_list.`name`
FROM `eve_mining_op_members`
INNER JOIN eve_member_list ON eve_mining_op_members.characterID = eve_member_list.characterID
WHERE op_id = '20110821105414-741653460';
My issue is that I have two different member lists, one lists are members that belong to our group and the second list is a list of members that do not belong to our group.
How do i write this query so that if a member is not found in the eve_member_list table it will look in the eve_nonmember_member_list table to match the eve_mining_op_members.characterID to the charName
I apologize in advance if the question is hard to read as I am not quite sure how to properly ask what it is that I am looking for.
Change your INNER JOIN to a LEFT JOIN and join with both the tables. Use IFNULL to select the name if it appears in the first table, but if it is NULL (because no match was found) then it will use the value found from the second table.
SELECT
characterID,
IFNULL(eve_member_list.name, eve_nonmember_member_list.charName) AS name
FROM eve_mining_op_members
LEFT JOIN eve_member_list USING (characterID)
LEFT JOIN eve_nonmember_member_list USING (characterID)
WHERE op_id = '20110821105414-741653460';
If you have control of the database design you should also consider if it is possible to redesign your database so that both members and non-members are stored in the same table. You could for example use a boolean to specify whether or not they are members. Or you could create a person table and have information that is only relevant to members stored in a separate memberinfo table with an nullable foreign key from the person table to the memberinfo table. This will make queries relating to both members and non-members easier to write and perform better.
You could try a left join on both tables, and then selecting the non-null results from the resulting query -
select * from
(select * from
eve_mining_op_members as x
left join eve_member_list as y1 on x.characterID = y1.characterID
left join eve_member_list2 as y2 on x.characterID = y2.characterID) as t
where t.name is not null
Or, you could try the same thing with a union and using inner join (assuming joined tables are the same):
select * from
(select * from eve_mining_op_members as x
inner join eve_member_list as y1 on x.characterID = y1.characterID
UNION
select * from eve_mining_op_members as x
inner join eve_member_list2 as y2 on x.characterID = y2.characterID) as t
You can throw in your op_id condition where you see fit (sorry, I didn't really understand where it came from). Good luck!
You have several options but by
using a UNION between the eve_member_list and eve_nonmember_member_list table
and JOIN the results of this UNION with your original eve_mining_op_members table
you will get your required results.
SQL Statement
SELECT lst.`characterID`
, lst.`name`
FROM `eve_mining_op_members` AS m
INNER JOIN (
SELECT characterID
, name
FROM eve_member_list
UNION ALL
SELECT characterID
, name
FROM eve_nonmember_member_list
) AS lst ON lst.characterID = m.characterID
WHERE op_id = '20110821105414-741653460';