I am trying to create a MYSQL query that pulls in data from a range of tables. I have a master bookings table and an invoice table where I am recording invoice id's etc from Stripe.
I am storing two invoices per booking; one a deposit, the second the final balance.
In my admin backend I then display to the admin info on whether the invoice is paid etc so need to pull in data from SQL to show this.
I'm following some previous guidance here What's the best way to join on the same table twice?.
My query is returning data, however when the invoices table is included twice (to give me the deposit and balance invoices) however the column names are identical.
Could someone point me in the right direction? I think I need to somehow rename the columns on the second returned invoice??? Sorry new to anything but basic SQL queries.
This is my SQL
SELECT * FROM bookings
INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
LEFT JOIN invoices ON bookings.booking_stripeDepositInvoice = invoices.invoice_id
LEFT JOIN invoices inv2 ON bookings.booking_stripeBalanceInvoice = inv2.invoice_id
Thanks to #Algef Almocera's answer I have amended my SQL (and stopped being lazy by using SELECT *, was able to trim loads of columns down to not many!)
SELECT
bookings.booking_status,
bookings.booking_reference,
bookings.booking_stripeCustomerReference,
bookings.booking_stripeDepositInvoice,
bookings.booking_stripeBalanceInvoice,
bookings.booking_totalPaid,
bookings.booking_voyageID,
bookings.booking_firstName,
bookings.booking_lastName,
bookings.booking_contractName,
bookings.booking_contractEmail,
voyages.voyage_id,
voyages.voyage_name,
voyages.voyage_startDate,
depositInvoice.invoice_id AS depositInvoice_id,
depositInvoice.invoice_status AS depositInvoice_status,
balanceInvoice.invoice_id AS balanceInvoice_id,
balanceInvoice.invoice_status AS balanceInvoice_status
FROM bookings
INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
LEFT JOIN invoices depositInvoice ON bookings.booking_stripeDepositInvoice = depositInvoice.invoice_id
LEFT JOIN invoices balanceInvoice ON bookings.booking_stripeBalanceInvoice = balanceInvoice.invoice_id
This, sometimes, couldn't be avoided as keywords might actually often be the same but of different purpose per table. To help with that, you can use aliases. for example:
SELECT
invoices.column_name AS invoices_column_name,
transactions.column_name AS transactions_column_name
FROM invoices ...
LEFT JOIN transactions ...
Related
I am trying to make a table that includes join between 3 tables in the MSSS 2008. There is a fact table, a date table, and a course table. I should join them to make a base table. In date table there is a one parameter that name is Academic Year lookup, and the values in this parameter is like 2000/1, 2001/2. This parameter in the base table should separate to three parameter such as CensusYear, StartYear, and ApplicationYear. Therefore, I need the data table multiple times. I executed a inner join query, and already I have four inner join statement, but I am getting some extra years, and I'm losing some years. I believe, my query should be wrong somewhere.
The attached file is include the design view that created in the MS Access, it'll help to see the tables, and understand what I need to create.
[Design View in Ms Access][1]
SELECT
A.[EventCount],
B.[AcademicYearLookup] AS [CensusYear],
C.[AcademicYearLookup] AS [StartYear],
D.[AcademicYearLookup] AS [ApplicationYear],
B.[CurrentWeekComparisonFlag],
B.[AcademicWeekOfYear],
case
when A.[ApplicationCensusSK] = 1 then 'Same Year'
when A.[ApplicationCensusSK] = 2 then 'Next Year'
when A.[ApplicationCensusSK] = 5 then 'Last Year'
ELSE 'Other'
END as [CensusYearDescription],
B.[CurrentAcademicYear],
A.[StudentCodeBK],
A.[ApplicationSequenceNoBK],
A.[CourseSK],
A.[CourseGroupSK],
A.[CourseMoaSK],
A.[CboSK],
A.[CourseTaughtAbroadSK],
A.[ApplicationStatusSK],
A.[ApplicationFeeStatusSK],
A.[DecisionResponseSK],
A.[NationalityCountrySK],
A.[DomicileCountrySK],
A.[TargetRegionSK],
A.[InternationalSponsorSK] INTO dbo.[BaseTable3yrs]
FROM Student.FactApplicationSnapshot A
INNER JOIN Conformed.DimDate AS B ON A.[CensusDateSK] = B.[DateSK]
INNER JOIN Conformed.DimDate AS C ON A.[AcademicYearStartDateSK] = C.[DateSK]
INNER JOIN Conformed.DimDate AS D ON A.[ApplicationDateSK] = D.[DateSK]
INNER JOIN Student.DimCourse ON A.CourseSK = Student.DimCourse.CourseSK
WHERE (((B.CurrentAcademicYear) In (0,-1))
AND ((A.ApplicationCensusSK) In (1,2,5))
AND ((Student.DimCourse.DepartmentShortName)= 'TEACH ED'));
/* the query to check that the result it's correct or not, and I check it by academic week of year, and I found that I am lossing some data, and I have some extra data, means maybe join is wrong*/
select * from [BaseTable3yrs]
where [StudentCodeBK]= '26002423'
AND [ApplicationSequenceNoBK] = '0101'
order by [AcademicWeekOfYear]
When doing recursive joins like this, it's easy to get duplicate records. You could try gathering the Conformed data separately into a table variable and then joining to it. This would also make your query more readable.
You might also try a SELECT DISTINCT on your main query.
I have 3 tables "Employees", "EmployeeLeaveDays" and "EmployeeLeaves".
I'm looking to create a view that displays the date of the leave and the employee name. So in order for my calendar to work I have split everyones leave into individual days(EmployeeLeaveDays) which has an FK that links each day back to (EmployeeLeaves) which has other details around the leave, in EmployeeLeaves I have a column "employee" which is an FK back to employees which contains the name.
So In my view I want to return the name as you can see is 2 tables away, I've wrote this MySQL query but it doesn't work (returns no data), I'm wondering if there is anyway to do what I need to do?
SELECT
EmployeeLeaveDays.id,
EmployeeLeaveDays.employee_leave,
EmployeeLeaveDays.leave_date,
EmployeeLeaveDays.leave_type
FROM EmployeeLeaveDays
INNER JOIN EmployeeLeaves
ON EmployeeLeaveDays.employee_leave=EmployeeLeaves.employee
INNER JOIN Employees
ON EmployeeLeaves.employee=Employees.employee_id;
Hopefully from that you're able to see what I'm trying to achieve, how ever I've attached some screenshots of the table structure.
Thanks
After some thinking I got there in the end. Here's the final query.
SELECT
EmployeeLeaveDays.id,
EmployeeLeaveDays.employee_leave,
EmployeeLeaveDays.leave_date,
EmployeeLeaveDays.leave_type,
EmployeeLeaves.employee,
Employees.employee_id,
Employees.first_name,
Employees.last_name
FROM EmployeeLeaveDays
LEFT JOIN EmployeeLeaves ON EmployeeLeaveDays.employee_leave = EmployeeLeaves.id
LEFT JOIN Employees ON EmployeeLeaves.employee = Employees.id;
I have two tables usersin and usersout(I can not change schema, a lot of system changes must be done in php otherwise). I should get all user records in a query but I should mark them if they are in or out also a user may have an in record and out record I shouldn't show in record if has an out record.
I have created tables with sample data in SQL Fiddle: http://www.sqlfiddle.com/#!9/ac99a/1/0
Can u help me how can I remove duplicates of user records in this union query?
If you want to have all entries with an entry in either the in or out table, but not in both of them, then a full outer join would be your friend.
Since MySQL does not know that kind of join, you can emulate it with a left outer join and a right outer join combined like so:
SELECT
ui.id, ui.user, 'i'
FROM
usersIN ui
LEFT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE uo.id IS NULL
UNION
SELECT
uo.id, uo.user, 'o'
FROM
usersIN ui
RIGHT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE ui.id IS NULL;
This should give you the right output.
A good visual explanation of joins can be found here
I'm aware of the INSERT INTO table_name QUERY; however, I'm unsure how to go about achieving the desired result in this case.
Here's a slightly contrived example to explain what I'm looking for, but I'm afraid I cannot put it more succiently.
I have two tables in a database designed for a hotel.
BOOKING and CUSTOMER_BOOKING
Where BOOKING contains PK_room_number, room_type, etc. and CUSTOMER_BOOKING contains FK_room_number, FK_cusomer_id
CUSTOMER_BOOKING is a linking table (many customers can make many bookings, and many bookings can consist of many customers).
Ultimately, in the application back-end I want to be able to list all rooms that have less than 3 customers associated with them. I could execute this a separate query and save the result in the server-side scripting.
However, a more elegant solution (from my point of view) is to store this within the BOOKING table itself. That is to add a column no_of_bookings that counts the number of times the current PK_room_number appears as the foreign key FK_room_number within the CUSTOMER_BOOKING table. And why do this instead? Because it would be impossible for me to write a single complicated query which will both include the information from all ROOMS, among other tables, and also count the occurrences of bookings, without excluding ROOMS that don't have any bookings. A very bad thing for a hotel website attempting to show free rooms!
So it would look like this
BOOKING: PK_room_number (104B) room_type (double) room_price (high), no_of_bookings (3)
BOOKING: PK_room_number (108C) room_type (single) room_price (low), no_of_bookings (1)
CUSTOMER_BOOKING: FK_room_number (104B) FK_customer_id (4312)
CUSTOMER_BOOKING: FK_room_number (104B) FK_customer_id (6372)
CUSTOMER_BOOKING: FK_room_number (104B) FK_customer_id (1112)
CUSTOMER_BOOKING: FK_room_number (108C) FK_customer_id (9181)
How would I go about creating this?
Because it would be impossible for me to write a single complicated
query which will both include the information from all ROOMS, among
other tables, and also count the occurrences of bookings, without
excluding ROOMS that don't have any bookings.
I wouldn't say it's impossible and unless you're running into performance issues, it's easier to implement than adding a new summary column:
select b.*, count(cb.room_number)
from bookings b
left join customer_booking cb on b.room_number = cb.room_number
group by b.room_number
Depending on your query may need to use a derived table containing the booking counts for each room instead instead
select b.*, coalesce(t1.number_of_bookings,0) number_of_bookings
from bookings b
left join (
select room_number, count(*) number_of_bookings
from customer_booking
group by room_number
) t1 on t1.room_number = b.room_number
You have to left join the derived table and select coalesce(t1.number_of_bookings,0) in case a room does not have any entries in the derived table (i.e. 0 bookings).
A summary column is a good idea when you're running into performance issues with counting the # of bookings each time. In that case I recommend creating insert and delete triggers on the customer_booking table that either increment or decrement the number_of_bookings column.
You could do it in a single straight select like this:
select DISTINCT
b1.room_pk,
c1.no_of_bookings
from cust_bookings b1,
(select room_pk, count(1) as no_of_bookings
from cust_bookings
group by room_pk) c1
where b1.room_pk = c1.room_pk
having c1.no_of_bookings < 3
Sorry i used my own table names to test it but you should figure it out easily enough. Also, the "having" line is only there to limit the rows returned to rooms with less than 3 bookings. If you remove that line you will get everything and could use the same sql to update a column on the bookings table if you still want to go that route.
Consider below solutions.
A simple aggregate query to count the customers per each booking:
SELECT b.PK_room_number, Count(c.FK_customer_id)
FROM Booking b
INNER JOIN Customer_Booking c ON b.PK_room_number = c.FK_room_number
GROUP BY b.PK_room_number
HAVING Count(c.FK_customer_id) < 3; # ADD 3 ROOM MAX FILTER
And if you intend to use a new column no_of_booking, here is an update query (using aggregate subquery) to run right after inserting new value from web frontend:
UPDATE Booking b
INNER JOIN
(SELECT b.PK_room_number, Count(c.FK_customer_id) As customercount
FROM Booking b
INNER JOIN Customer_Booking c ON b.PK_room_number = c.FK_room_number
GROUP BY b.PK_room_number) As r
ON b.PK_room_number = r.PK_room_number
SET b.no_of_booking = r.customercount;
the following generates a list showing all of the bookings and a flag of 0 or 1 if the the room has a customer for each of the rooms. it will display some rooms multiple times if there are multiple customers.
select BOOKING.*,
case CUSTOMER_BOOKING.FK_ROOM_NUMBER is null THEN 0 ELSE 1 END AS BOOKING_FLAG
from BOOKING LEFT OUTER JOIN CUSTOMER_BOOKING
ON BOOKING.PK_room_numer = CUSTOMER_BOOKING.FK_room_number
summing and grouping we arrive at:
select BOOKING.*,
SUM(case when CUSTOMER_BOOKING.FK_ROOM_NUMBER is null THEN 0 ELSE 1 END) AS BOOKING_COUNT
from BOOKING LEFT OUTER JOIN CUSTOMER_BOOKING
ON BOOKING.PK_room_number = CUSTOMER_BOOKING.FK_room_number
GROUP BY BOOKING.PK_room_number
there are at least two other solutions I can think of off the top of my head...
I have three tables. Estimates, Estimate_versions, and customers.
Here is some SQL
SELECT estimates.id,
estimates.estimate_number,
estimates.description,
estimates.meeting_date,
estimates.job_date,
estimates.status,
estimates.price
FROM
(estimates)
LEFT OUTER JOIN estimate_versions estimate_versions ON estimate_versions.estimate_id = estimates.id
LEFT OUTER JOIN customers customers ON customers.id = estimates.customer_id
WHERE customers.key = 'JsB4ND90bn'
This works -- What I want to do is add a field at the very end of the table.
Essentially, I want it to 'count', the number of records in estimate_versions, that contain the current rows, estimate.id, here is some non-working pseudocode of what I basically want in the final field
count(where estimate_versions.estimate_id = estimates.id)
When I try and do a few different ways of achieving this, I usually get ONE row of data, with one number in it. Instead of lets say, 3 records, and the count field containing the appropriate number.
Looking forward to receiving some much needed aid, my SQL skills are weak.
I think this is what you are looking for.
SELECT estimates.id,
estimates.estimate_number,
estimates.description,
estimates.meeting_date,
estimates.job_date,
estimates.status,
estimates.price,
count(estimate_versions.estimate_id)
FROM
(estimates)
LEFT OUTER JOIN estimate_versions estimate_versions ON estimates.id = estimate_versions.estimate_id
LEFT OUTER JOIN customers customers ON estimates.customer_id = customers.id
WHERE customers.key = 'JsB4ND90bn'
group by
estimates.id,
estimates.estimate_number,
estimates.description,
estimates.meeting_date,
estimates.job_date,
estimates.status,
estimates.price