Join 3 tables on mysql in specific situation - mysql

Hi I'm a newbie to this and I'm attempting to join 3 different tables:
Invoice: CustID, VIN, InvoiceType
Customer: CustID, Zip
Zipcode: Zip, City
I know I need to use a join clause but I'm not exactly sure how to show the specific City of the associated customer tied to the invoice along with all fields provided in invoice and show a specific InvoiceType. Here is what I currently have and I'm really where to go next or what other options to consider.
SELECT invoiceno, invoice.customerid, vin, invoicetype, city
FROM invoice, customer, zip
WHERE invoicetype = 'sell'

try this
select
i.CustID,
i.VIN,
i.InvoiceType,
c.CustID,
z.Zip,
z.City
from
Invoice i
inner join
Customer c
on i.CustID=c.CustID
inner join
zip z
on c.zip=z.zip
WHERE
i.invoicetype = 'sell'

Related

MySQL, Join two tables with one table?

I have one table customer, and one bill, and one sell.
Customer table
id-----name
Bill table
id-----customer_id
Sell table
id-----customer_id-----bill_id-----qtt-----price
A customer can have the records in the sell table with customer_id, and also have the bill record in the bill table with customer_id and this bill record has record in the sell table with bill_id.
This means a customer can have direct or indirect (in this case by passing the bill table) with sell table.
Now how to join tables that retrieve the total sell of a customer with ascending or deciding order?
Any idea?
I have tried many ways for example something like below, but none of them was working:
SELECT
sell.id AS sell_id,
customer.id,
bill.id AS bill_id,
customer.`name`,
sell.quantity*sell.price AS sell_price
FROM
customer_tb customer
JOIN bill ON bill.customer_id = customer.id
JOIN sell ON sell.customer_id = customer.id OR sell.bill_id = bill.id
NOTE: In case of bill table has a record in the sell table, the customer_id column is NULL and also same for the customer sell record the bill_id is NULL, this means in the sell table in the same entry only one of the (customer_id, bill_id) column has value.
You have the customer column in your sell tables, you don't need to join with bill table.
SELECT
customer.id,
customer.name,
SUM(sell.quantity * sell.price) AS total_amount
FROM customer_tb as customer
INNER JOIN sell
On sell.customer_id = customer.id
GROUP BY customer.id
You have to group your rows by the customer to get their sum independently
Your challenge is to look up the correct Customer.name for each Sell row.
You need to join Sell to Customer, and also join Sell to Bill to Customer.
How to do this?
FROM Sell s
LEFT JOIN Cust c1 ON s.customer_id = c1.id
LEFT JOIN Bill b on s.bill_id = b.id
LEFT JOIN Cust c2 ON b.customer_id = c2.id
That gives us:
s.id: the Sale id
s.quantity, s.price: the business details of the Sale
c1.name: the Customer name directly from the Sale's customer_id
c2.name: the Customer name indirectly through the Sale's bill_id
Because we use LEFT JOINs, either name can be NULL depending on which ids are null. And, I believe you favor using the direct name over the indirect name if you have both.
That means we use COALESCE() to choose one name from the two. Something like this
SELECT s.id, s.Quantity, s.Price,
COALESCE (c1.name, c2.name) name,
COALESCE (c1.id, c2.id) customer_id
FROM Sell s
LEFT JOIN Cust c1 ON s.customer_id = c1.id
LEFT JOIN Bill b on s.bill_id = b.id
LEFT JOIN Cust c2 ON b.customer_id = c2.id
But, if you have a chance to rework this database before you put a ton of data into it, please consider redesigning things to get rid of this ambiguity. It's going to drive you mad and cost you bigger servers if you have to make it work well with megarows.

join three tables or use nested queries with IN

(a) List the names of the cities (from table City) whose name starts with 'p' and are in France (from table Country.
(b) List all columns from the Patient table for the patient's whose email contains '#gmail.com' and are from Atlanta
I have tried to join these tables but I do not seem know which values to join together
select city_name, email, first_name, last_name, pid, title, address_id, gender
from City c join Patient p on c.city_name = p.address_id
where p.email like '#gmail.com%'and c.city_name like 'Atlanta%
The result is supposed to show cities in France that start with 'p' and patients within a table whose email contains #gmail.com and that live in Atlanta.
You should not link the city name with the address id (c.city_name = p.address_id). Similar fields (usually primary and foreign keys) that contain the same structure (type, length, etc.) should be linked.
Since you are using the address ID, the address table must also be added as it contains the city ID. Regarding email search, "contains" means that it may be in the middle, so you must allow any characters at the beginning as well.
Try something like this:
select
c.city_name, p.email, p.first_name, p.last_name, pid, title, p.address_id, p.gender
from Patient as p
join Address as a on p.address_id = a.address_id
join City as c on c.city_id = a.city_id
where p.email like '%#gmail.com%'
and c.city_name = 'Atlanta'

Why does my Query return "Empty set (0.00 sec)"?

SOLVED-run UPDATE building SET building_name = "Main Street Building" WHERE building_id = 2;
From there, the task 3 query will return proper results.
Task One:
Query:
SELECT first_name, last_name, building_name, room.room_id, meeting_start,meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND person.first_name='Tom'
AND person.last_name='Hanks';
Task Two:
Query:
SELECT first_name, last_name, building_name, room.room_id, meeting_start,meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND meeting.meeting_id=2;
Task Three:
Query:
SELECT first_name, last_name, building_name, room.room_id,meeting.meeting_id, meeting_start, meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND building_name='Main Street Building';
Task Four:
Query:
SELECT count(person_id) 'Count of meeting attendees', meeting.meeting_id,meeting_start,meeting_end
FROM meeting, person_meeting
WHERE meeting.meeting_id=person_meeting.meeting_id
GROUP BY meeting.meeting_id;
Task Five:
Query:
SELECT first_name, last_name, meeting.meeting_id, meeting_start, meeting_end
FROM meeting INNER JOIN person_meeting ON meeting.meeting_id=person_meeting.meeting_id
INNER JOIN person ON person.person_id=person_meeting.person_id
AND meeting_start<'2016-12-25 12.00.00';
Task 1,2,4,5 and 5 all run perfectly. if you all need the task prompts, let me know.
Note: I haven't test this yet.
I changed the queries based on our recent interaction.
This is your original
SELECT first_name, last_name, building_name, room.room_id,meeting.meeting_id, meeting_start, meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND building_name='Main Street Building';
This is the way I would try to build it
Based on page 2 and 3 in the document, you provided, https://snhu.brightspace.com/d2l/lor/viewer/viewFile.d2lfile/76437/9523,2/, I would do the following:
First, I would obtain information about the building.
SELECT building_id
FROM building
WHERE building_name like '%Main Street Building%';
Note: I am assuming that the building name is correct. However, just in case, I am using the wildcard % before and after the name
Next, I would obtain the information about the room:
SELECT b.building_name, r.room_id
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
WHERE b.building_name like '%Main Street Building%';
Following that, I would obtain the information about the meeting:
SELECT b.building_name, r.room_id, m.meeting_id, m.meeting_start, m.meeting_end
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
LEFT JOIN meeting m
ON r.room_id = m.room_id
WHERE b.building_name like '%Main Street Building%';
Finally, I would obtain the information of the IDs of people that will be in that meeting and show their names:
SELECT b.building_name, r.room_id, m.meeting_id, m.meeting_start, m.meeting_end, p.first_name, p.last_name
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
LEFT JOIN meeting m
ON r.room_id = m.room_id
LEFT JOIN persom_meeting pm
ON m.meeting_id = pm.meeting_id
LEFT JOIN person p
ON pm.person_id = p.person_id
WHERE b.building_name like '%Main Street Building%';
If by any chance, these queries do not work, I would advice that you ensure that the relationships exists between the tables.
This means that there should be a building_id match, a room_id match, a meeting_id match and a person_id match between the tables. Plus, I would check that the building name is spelled correctly since its case-sensitive.
The reason I use LEFT JOINs is so I can display all the information of the previous tables (all the rows) plus the records in which the IDs match the foreign keys IDs. As explained here: http://www.acarlstein.com/?p=4168
Also, in http://www.acarlstein.com/?p=4194, I am showing how a Two Left (Outer)Joins would work.
However, in your case, it is more like a chain that is being build so it doesn't match the diagram but you can perhaps get the idea of what I mean.

MySQL, Show value of column if match exist else leave as null

I'm sure this has been asked before but can't find the answer.
I have 3 tables OWNER, CAR, HOUSE
OWNER has 2 columns id and name
CAR has 3 columns id, ownerId and cartype
HOUSE has 4 columns id, ownerId, address, country
I want to write a SQL query that gets the owners name, cartypes, and addresses that are in Sweden
Here comes the tricky part. I want all the owners names and cartypes in the result table even if they don't own a house in Sweden. Can I get all that in 1 query or do I need to use 2? How would that query look?
You should be able to accomplish this with a simple left join:
SELECT O.name, C.cartype, H.address, H.country
FROM OWNER AS O
JOIN CAR AS C ON O.id = C.ownerid
LEFT JOIN HOUSE AS H ON O.id = H.ownerid AND Ucase(H.country) = "SWEDEN"
This will always give you a list of owners and their car types, in addition, it will give you a list of those that also happen to have a house address in sweden.
First you need to join the table then add new column in query by using CASE to check
SELECT o.* , c.* ,h.*,
(CASE WHEN h.county ='sweden' THEN h.county ELSE NULL END) AS HasCountry
FROM OWNER o
JOIN CAR c ON (c.ownerId =o.id)
JOIN HOUSE h ON (h.ownerId =o.id)

How can I write this query to filter the results properly?

I have 3 tables I am wanting to join:
equipment
equipmentNo
assetNo
subCategoryNo
doNo
userNo
locationNo
isocNo
emergency
ariNo
makeNo
modelNo
serial
kitNo
purchaseDate
purchasePrice
comments
surplused
employees
userNo
fname
lname
doNo
emergency
subcategories
subCategoryNo
subCategory
categoryNo
replacementCycle
I need to get a set of data that includes all of the equipment information ordered by 'doNo' and 'lname' from employees which are linked by 'userNo' and the equipment 'subCategoryNo' needs to be only those from subcategories where 'categoryNo' equals 2.
I got this far before getting lost and confused.
SELECT equipment.*, employees.lname, employees.fname
FROM equipment
LEFT JOIN employees
USING (userNo)
ORDER BY equipment.doNo, employees.lname;
I could not figure out how to limit this to only 'categoryNo' 2;
SELECT equipment.*, employees.lname, employees.fname
FROM equipment
LEFT JOIN employees USING (userNo)
JOIN subcategories USING(subCategoryNo)
WHERE subcategories.categoryNo=2
ORDER BY equipment.doNo, employees.lname;