Select rows based on an array of values and join data - mysql

I have a MySQL database of contacts with three tables.
person
personContact
personDetails
Each contact shares a primary key called 'ID'
The personContact table contains a value called 'personZip' which happens to be their mailing address zip code.
I'd like to write a SQL query that will give me all the contact data for each person in a specific array of zip codes.
I've written a simple statement to perform an inner join on 2 of the tables:
SELECT * FROM `personContact`
INNER JOIN person
ON personContact.ID=person.ID
I've written a statement to select only the zip codes I need:
SELECT * FROM 'personContact'
WHERE personContact.personZip=12564
OR personContact.personZip=12563
OR personContact.personZip=12522
OR personContact.personZip=12590
OR personContact.personZip=12594
OR personContact.personZip=12533
OR personContact.personZip=12570
OR personContact.personZip=12589
OR personContact.personZip=10509
I'm not sure how to perform two joins, to merge all columns from all three tables.
I'm not sure how to write the query to accommodate both the selection of zip codes and the JOINS.
MySQL errors are not helping me move in the right direction.

You were almost there. Use in which is equivalent to or.
SELECT pc.* --select columns from the other tables as needed.
FROM
`personContact` pc
INNER JOIN person p ON pc.ID = p.ID
INNER JOIN personDetails pd on pd.ID = p.ID
where pc.personzip in (12563, 12522, 10509) -- add more zips as needed

Join all three tables and return all columns while filtering by zip code:
SELECT person.*, personContact.*, personDetails.*
FROM person
INNER JOIN personContact ON personContact.ID = person.ID
INNER JOIN personDetails ON personDetails.ID = person.ID
WHERE personContact.personZip = 12564
OR personContact.personZip = 12563
OR personContact.personZip = 12522
OR personContact.personZip = 12590
OR personContact.personZip = 12594
OR personContact.personZip = 12533
OR personContact.personZip = 12570
OR personContact.personZip = 12589
OR personContact.personZip = 10509
EDIT: Multiple OR statements can be replaced using IN as others have suggested
WHERE personContact.personZip IN (12564, 12563, 12522, 12590 ...)

Related

Issue With Join Doubling Results

I have seen several posts about this on Stack Overflow, but none of them seems to give me an answer that I can understand.
I am trying to join several relations together in order to get all of the relevant information to output all routes that start in China and end in the United States.
In the SeaRoute relation, the start_port and end_port are stored as INT and in the Port relation the pid corresponds to the start_port and end_port and includes a pcountry column.
I am starting off with just trying to output everything that has a start_port that is in China. I am expecting 3 results from my Record relation as those are the only ones that start with China in the table; However, I am receiving 6 records at the output (all of the results appear to have been doubled if I go back and audit what's in the table).
While I want the right answer, I am more concerned that I have a fundamental misunderstanding of Inner Join and the other Join methods. What am I doing wrong?
SELECT *
FROM Record
INNER JOIN Goods AS Go_data
ON Record.gid = Go_data.gid
LEFT JOIN SeaRoute AS SR
ON Record.rid = SR.rid
RIGHT JOIN (SELECT pid, pcountry AS starting_port_country
FROM Port
INNER JOIN SeaRoute AS SR ON Port.pid = SR.start_port
WHERE Port.pcountry = 'China')
AS start_port_table ON SR.start_port = start_port_table.pid
From the looks of your query, you want to be INNER JOINing between the records that you have only on the routes that you want.
You know all of the SeaRoutes that start in China and end in the United States already, you do however need to join to the Ports table twice like so:
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
Then you just need to join that to your main query:
SELECT *
FROM Record
INNER JOIN dbo.Goods AS Go_data ON Record.gid = Go_data.gid
INNER JOIN
(
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
) ports ON ports.rid = Record.rid
There's no way I can explain joins to you any clearer than this page can:
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

Querying Many to Many When 3 Tables Connected to A junction

DB MODEL
I have Model Which is Connected in above Order Now I want to Select Style Names From Style Table.
Case 1 : I want the Style Names which are both intersecting Category and Gender
Case 2 : I want the Style Names which are intersecting Gender only regardless of category.
I am newbie to SQL is there any efficient way to Get the desired result using SQL JOINS . Any Help in such case will be appreciated or is there any modelling solutions to deal with such type of situations.
Here is how you would join your tables:
SELECT *
FROM `style`
INNER JOIN `StyleCategoryGender` ON `StyleCategoryGender`.`SID` = `style`.`Code`
INNER JOIN `StyleCategoryGender` ON `Category`.`Code` = `StyleCategoryGender`.`GID`
INNER JOIN `StyleCategoryGender` ON `Gender`.`Code` = `StyleCategoryGender`.`CID`
then you can add WHERE clauses as needed
SELECT *
FROM `style`
INNER JOIN `StyleCategoryGender` ON `StyleCategoryGender`.`SID` = `style`.`CODE`
INNER JOIN `StyleCategoryGender` ON `Category`.`Code` = `StyleCategoryGender`.`GID`
INNER JOIN `StyleCategoryGender` ON `Gender`.`Code` = `StyleCategoryGender`.`CID`
WHERE `Gender`.`Name` = 'Female'

sub-select query in SQL will not populated new column/field with specific text

How do I get my new field to populate with Yes or No rather than pre-existing data? In this case, I'm getting a new field called ESL but I can only get it to run if i populated the field with colleagueId. I want it to populate with Yes and not true with No. I've also tried case statements.
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm, ESL.colleagueId as ESL
from tbl_studentTerms st
left join
(select distinct colleagueId
from tbl_studentclasses
where enrolled = 1
and subject = 'ESL') as ESL
on ESL.colleagueId=st.colleagueId
inner join tbl_students s
on st.colleagueId = s.colleagueId
where s.endingCohort = '2009SP'
and st.term='2009SP'
and s.colleagueId in(select [Student ID] from dbo.pvt_SelectedStudents)
Here is one method:
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm,
coalesce(ESL.ESL, 'No') as ESL
from tbl_studentTerms st inner join
tbl_students s
on st.colleagueId = s.colleagueId left join
(select distinct colleagueId, 'Yes' as ESL
from tbl_studentclasses
where enrolled = 1 and subject = 'ESL'
) ESL
on ESL.colleagueId = st.colleagueId
where s.endingCohort = '2009SP' and st.term = '2009SP' and
s.colleagueId in (select [Student ID] from dbo.pvt_SelectedStudents);
Notes:
I move the inner join to be before the left join. I find it easiest to read query where inner joins come first, followed by left joins.
Do not use select distinct unless you really need to remove duplicates.

How do i deal with this situation for searching records in mysql?

i am developing a PHP/MYSQL search module, where i have to search tables based on many different criteria, i have some 11 tables, and i have used multiple joins to create one single MySQL query and based on WHERE clause i intend to search for specific records, here is the MYSQL Query that i am using.
SELECT
prop.id,
prop.serial,
prop.title,
prop.rating,
prop.addDate,
prop.approve,
prop.status,
prop.user_id as userId,
user_det.email as email,
user_det.name as name,
prop.area_id as areaId,
area.name as areaName,
area.zipCode as zipCode,
area.city_id as cityId,
city.name as cityName,
city.state_id as stateId,
state.name as stateName,
state.country_id as countryId,
country.name as countryName,
prop.subCategory_id as subCategoryId,
subCat.name as subCategoryName,
subCat.category_id as categoryId,
cat.name as categoryName,
prop.transaction_id as transactionId,
trans.name as transactionName,
price.area as landArea,
price.price as priceSqFt,
price.total_price as totalPrice,
features.bedroom,
features.bathroom,
features.balcony,
features.furnished,
features.floorNum,
features.totalFloor
FROM properties prop
LEFT JOIN user_details user_det ON (prop.user_id = user_det.user_id)
LEFT JOIN areas area ON (prop.area_id = area.id)
LEFT JOIN cities city ON (area.city_id = city.id)
LEFT JOIN states state ON (city.state_id = state.id)
LEFT JOIN countries country ON (state.country_id = country.id)
LEFT JOIN subCategories subCat ON (prop.subCategory_id = subCat.id)
LEFT JOIN categories cat ON (subCat.category_id = cat.id)
LEFT JOIN transactions trans ON (prop.transaction_id = trans.id)
LEFT JOIN prop_prices price ON (price.property_id = prop.id)
LEFT JOIN prop_features features ON (features.property_id = prop.id)
although all works well here, i have a situation where i have a table called prop_amenities below are the content of this table.
as the table above have multiple property_id if i query it using JOINS then mostly it will return duplicate records or single record omitting others depending on the type of JOIN i use. so instead i would like to deal it this way.
use the table prop_amenities to only deal with conditions not to return the result.
for example i am searching for a property with amenity id 1,5,9,17 and 24, then it should check if all the records exist in the prop_amenities table, i.e 1,5,9,17 and 24 in this case. and return the appropriate records with all above selected columns.
i am clueless on dealing this situation using MySQL. how do i go on this?
thank you..
You said "check if all the records exist in the prop_amenities table" and that's the key word here.
SELECT ...
FROM properties AS prop
LEFT JOIN ...
WHERE EXISTS (SELECT 1 FROM prop_amenities AS pa WHERE pa.property_id = prop.property_id AND pa.amenity_id = 7);

How to concatenate the output of a SQL query into one string

I am newbie in writing SQL queries and this is for a mySQL database.
I have a Table called PatientVisit (PV), which has a one to one with BillMaster (BM). Each visit has one bill, which then has a one to many with BillDetail (BD). When i list out the Visit details from PatientVisit (PV), i need to print a string with the set of 'ServiceName' columns associated with that one visit.
So for example, the PatientVisit.ID number '1' has a corresponding BillMaster.Bill No '1' which has 2 entries in BillDetail 'Consultation' and 'Dressing'.
When i print details of Visit 1, i need 'Consultation,Dressing' as one string value for the 'Service Name' column.
If i had a one to one , then the query would have been simple as follow :
select PV.ID, BM.BillNo, BD.ServiceName
FROM PatientVisits PV INNER JOIN BillMaster BM ON BM.VisitID = PV.ID
INNER JOIN BillDetail BD ON BD.BillNo = BM.BillNo
WHERE ....
However, since it is one to many for the ServiceName column, how can this query be written ?
Thanks,
Chak.
Try this
select PV.ID, BM.BillNo,
GROUP_CONCAT(BD.ServiceName)
FROM PatientVisits PV INNER JOIN BillMaster BM ON BM.VisitID = PV.ID
INNER JOIN BillDetail BD ON BD.BillNo = BM.BillNo
WHERE ..
GROUP BY PV.ID,BM.BillNo
..