How can I merge data from two SQL tables? - mysql

I have two tables. Table "alldates" consists of date column called "nextdate". Table "availability" consists of multiple columns including a date column called "availdate". The "alldates" table primary key is the column "nextdate". The "availability" table primary key is a column called "event_num".
For explanation purposes let's say table "alldates" is populated with 16 rows, dates 10/01/2014 through 10/16/2014 and table "availability" is populated with 9 rows, like so:
Availdate Event_num Event Description
10/01/2014 3 Joe's birthday
10/04/2014 12 Bill's dentist appt
10/04/2014 5 Buy pizza
10/05/2014 6 Clean the house
10/07/2014 7 Go to theater
10/07/2014 8 Continue forward
10/09/2014 9 Mow the grass
10/11/2014 10 Take a nap
10/15/2014 11 Fix the clock
I need to create a new table that looks like this:
Availdate Event_num Event Description
10/01/2014 3 Joe's birthday
10/02/2014 (from table "alldates")
10/03/2014 (from table "alldates")
10/04/2014 12 Bill's dentist appt
10/04/2014 5 Buy pizza
10/05/2014 6 Clean the house
10/06/2014 (from table "alldates")
10/07/2014 7 Go to theater
10/07/2014 8 Continue forward
10/08/2014 (from table "alldates")
10/09/2014 9 Mow the grass
10/10/2014 (from table "alldates")
10/11/2014 10 Take a nap
10/12/2014 (from table "alldates")
10/13/2014 (from table "alldates")
10/14/2014 (from table "alldates")
10/15/2014 11 Fix the clock
10/16/2014 (from table "alldates")

Looks like a classic left join to me.
select a.nextdate as availdate,
b.event_num,
b.event_description
from alldates a
left join availability b
on a.nextdate = b.availdate
;

If both the table have same number of columns then you can probably do a UNION between them and order by the Availdate column
select * from
(
select Availdate,
Event_num,
Event Description
from alldates
UNION
select Availdate,
Event_num,
Event Description
from availability
) tab
order by Availdate

What you want is a LEFT OUTER JOIN. LEFT OUTER tells SQL to include rows from the first table, even if they don't have corresponding entries in the second. "Corresponding" is determined by the predicate, which is a condition telling the database how rows in one table are associated with rows in the other.
The below query will select all rows from alldates. For those whose nextdate matches a row's availdate in availability, each it will be displayed once per matching row. For those whose nextdate doesn't match anything from availability, event_num and event_description will be listed as NULL.
SELECT
alldates.nextdate,
availability.event_num,
availability.event_description
FROM
ALLDATES
LEFT JOIN availability
ON alldates.nextdate = availability.availdate;

Related

MySQL iterate information from one table in to 2 columns in query

I have a database which holds maintenance reports for unique units that I need to pull information from in a single query. My issue is the convoluted way the information is stored.
SELECT date(reports.created_timestamp) as Date,
locations.name as Location,
location_groups.name as L_group,
units.name as Unit_name,
units.id as Unit_ID,
concat(users_2.first_name, "
",users_2.last_name) as Engineer,
reports.id as Report_ID
FROM reports
LEFT JOIN units
ON reports.unit_id = units.id
LEFT JOIN users_2
ON reports.user_id = users_2.id
LEFT JOIN locations
ON units.location_id = locations.id
LEFT JOIN location_groups
ON locations.locations_group_id = location_groups.id
where reports.created_timestamp >= '2022-01-01 00:00:00'
and locations.name NOT LIKE 'Company Vehicles'
and location_groups.name = 'Airports';
This returns:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
Report_ID
2022-10-18
Airport 1
Airports
AIR-AAA1-N127
1
Engineer 1
19471
2022-10-19
Airport 2
Airports
AIR-BBB2-D03
4
Engineer 2
19486
2022-10-19
Airport 2
Airports
AIR-BBB2-D14
13
Engineer 2
19495
2022-10-25
Airport 2
Airports
AIR-BBB2-D13
14
Engineer 2
19518
However, when the engineers are completing maintenance they have to do several tasks depending on the "unit" type. This is held in the units table as unit_type_id variable. This then references display_type_report_tasks to determine what tasks should be completed based on the unit_type_id, e.g:
id
unit_type_id
report_task_id
1
3
1
2
13
1
9
13
2
3
14
1
4
15
1
The report_task_id's then relate to table report_tasks which holds the following as an example:
id
name
text
description
1
Unit Cleaned-Internal
Unit Cleaned-Internal
Unit Cleaned-Internal
2
Unit Cleaned-External
Unit Cleaned-External
Unit Cleaned-External
3
Bumper Bar Fixed
Bumper Bar Fixed
Bumper Bar Fixed
4
Tile Replaced
Tile Replaced
Tile Replaced
5
Hardware Replaced
Hardware Replaced
Hardware Replaced
Picking unit type 13 as an example, when an engineer completes a report, the task options are stored in reports_tasks_selected_options such as the following:
id
report_tasks_option_id
example_report_id
30452
1
19558
30453
9
19558
The report_tasks_option_id then relates to report_tasks_options:
id
value
description
report_task_id
1
1
Not cleaned
1
2
2
Internal Clean
1
3
3
Deep Clean
1
7
1
Not cleaned
2
8
2
External Clean
2
9
3
Deep Clean
2
I want to query the unit_type_id and dynamically assign the column headers using report_tasks.name depending on what unit types are returned. (If a unit is returned that doesn't utilise all columns then NULL is used where no result is returned.)
I have to build reports per unit_type and statically assign the columns, BUT I cannot figure out how to then iterate through reports_tasks_selected_options to get the report_tasks_options.description for the results. As an example (using report_id = 19558) my current query output would be:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
2022-11-01
Airport 3
Airports
AIR-CCC1-D09
1907
Engineer 3
But because I know this is unit_type=13 I know that the report_tasks related to it are Unit Cleaned-Internal and Unit Cleaned-External. So I want to iterate through the reports_tasks_selected_options table for that report number (As I know that the lower ID is always Unit Cleaned-Internal because it has the lower ID in report_tasks, and so the higher ID from reports_tasks_selected_options is always going to be Unit Cleaned-External.)
Desired output:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
Report_ID
Clean-Int
Clean-Ext
2022-11-01
Airport 3
Airports
AIR-CCC1-D09
1907
Engineer 3
19558
Not cleaned (1)
Deep Clean (9)
I put the option numbers in brackets for clarity but do not require them in my output.

Select and compare two columns from different tables to find matched records

I'm just learning PHP and MySQL and I have two tables in the same database : FirstYear , SecondYear that have a structure like this :
StudentId |Math | Physics StudentId1 | Math1 | physics1
Joe 10 14 Alan 12 17
Alan 13 17 Smith 11 13
Smith 9 9 Joe 10 15
Is it possible to write a query that select and compare the two columns StudentId , StudentId1 to find matched records and if for example Joe=Joe after that compare records of math with math1 and physics with physics1 that are in the same row as matched records of StudentId with StudentId1 ;the idea of this query is to study the improvement of same student from first year to the second one ,Thanks .
Yes, it is possible but you have to complete SQL fundamental course.
In this situation you have to know about JOIN. Such as, Inner Join, Left Join, Right Join, Full Join etc. Also, compare with unique id, not name. Because, name always duplicate. It is not good practice. So, Know about primary key and foreign key.
However,
Query-
SELECT * FROM FirstYear INNER JOIN SecondYear ON FirstYear.StudentId = SecondYear.StudentId1 WHERE FirstYear.id = 1
Something like that, alternatively, you can try to another logic.

Find next occurrence from a reference table sql

I have searched many other questions, but cant find a usable comparison. I have a SQL table that has a list of all the rooms at our hotel. I want to know the next time each room is going to be occupied. There are two tables I am looking at, one contains the name and details of each room we have, for all intents it is a static table. The other table is a reservations table that shows check in and check out times, and has a column that references which room is being used.
Table Rooms
unique id name
1 Room 3
2 Room 4
3 Suite 1
4 Suite 2
5 Suite 3
Table Reservations
unique id start date room id
1 12/4/16 3
2 12/4/16 4
3 12/6/16 3
4 12/12/16 3
5 12/14/16 2
6 12/20/16 2
This would return only 3 values:
2 12/20/16
3 12/4/16
4 12/4/16
If also possible I would like the make it so that if a reservation is not found a null value is returned, so ultimately, the return value would be
Room Next Occurrence
1 null
2 12/20/16
3 12/4/16
4 12/4/16
5 null
Is there a way of doing this without my current php hack that runs 200 sql queries?
Thanks so much!
You can use left join
select rooms.id, rooms.name, reservations.`start date`
from Rooms
left join reservations on reservations.`room id` = Rooms.id
order by rooms.id

T-SQL query procedure-insert

I am wondering if any of you would be able to help me. I am trying to loop through table 1 (which has duplicate values of the plant codes) and based on the unique plant codes, create a new record for the two other tables. For each unique Plant code I want to create a new row in the other two tables and regarding the non unique PtypeID I link any one of the PTypeID's for all inserts it doesnt matter which I choose and for the rest of the fields like name etc. I would like to set those myself, I am just stuck on the logic of how to insert based on looping through a certain table and adding to another. So here is the data:
Table 1
PlantCode PlantID PTypeID
MEX 1 10
USA 2 11
USA 2 12
AUS 3 13
CHL 4 14
Table 2
PTypeID PtypeName PRID
123 Supplier 1
23 General 2
45 Customer 3
90 Broker 4
90 Broker 5
Table 3
PCreatedDate PRID PRName
2005-03-21 14:44:27.157 1 Classification
2005-03-29 00:00:00.000 2 Follow Up
2005-04-13 09:27:17.720 3 Step 1
2005-04-13 10:31:37.680 4 Step 2
2005-04-13 10:32:17.663 5 General Process
Any help at all would be greatly appreciated
I'm unclear on what relationship there is between Table 1 and either of the other two, so this is going to be a bit general.
First, there are two options and both require a select statement to get the unique values of PlantCode out of table1, along with one of the PTypeId's associated with it, so let's do that:
select PlantCode, min(PTypeId)
from table1
group by PlantCode;
This gets the lowest valued PTypeId associated with the PlantCode. You could use max(PTypeId) instead which gets the highest value if you wanted: for 'USA' min will give you 11 and max will give you 12.
Having selected that data you can either write some code (C#, C++, java, whatever) to read through the results row by row and insert new data into table2 and table3. I'm not going to show that, but I'll show how the do it using pure SQL.
insert into table2 (PTypeId, PTypeName, PRID)
select PTypeId, 'YourChoiceOfName', 24 -- set PRID to 24 for all
from
(
select PlantCode, min(PTypeId) as PTypeId
from table1
group by PlantCode
) x;
and follow that with a similar insert.... select... for table3.
Hope that helps.

SQL query for multiple (one-to-many) tables in mysql database

I have a database with tours (group city tours with guide). What I need is a SQL query (for a mysql 5.1.54 database) that will eventually give me a PHP array with the information out of multiple tables combined. I'm able to accomplish this by doing a query just for the first 3 tables and then adding the information in table 4 and 5 within a foreach loop.
But, I need to use the query for searching/filtering (like: show all reservations where partner has id 9) so I need SQL to select the corresponding reservations.
Reservations with no partners (table 4) and/or guides (table 5) must be included.
All partners and guides must be included in the result (reservation can have more partners/guides)
All information in table 4 and 5 must be included (like the status from table 4).
A simplified version of the database:
Table 1: reservations:
id id_client id_tour
1 22 6
2 23 5
Table 2: clients (one reservation has one client):
id name
22 John
23 William
Table 3: tours (one reservation has one tour)
id name
5 big tour
6 small tour
Table 4: partners (one reservation can have multiple partners):
id id_reservation id_partner_type id_partner status
34 1 9 16 1
35 1 9 17 0
Table 5: guides (one reservation can have multiple guides):
id id_reservation id_guide
18 1 14
19 1 15
I have tried to work this out but I just can not get a query that does the job. I used GROUP_CONCAT to get the multiple partner and guide id's. Biggest problem I have is not being able to include the reservations that have no partners and/or guides like reservation 2.
To include all reservations that have no partners and guides you need to use OUTER JOINs, for example the following query will gives you all information from your tables 4, 5 including your condition:
Select p.*, g.*
from reservations r
left outer join partners p on p.id_reservation = r.id
left outer join guides g on g.id_reservation = r.id
where p.id_reservation is null and g.id_reservation is null