Development of railway enquiry system, how to model Trains, Stations and Stops? - mysql

For example, if I have two trains, X and Y and they travel:
TRAIN.........STATIONS
Train-X : Goes Via Station-A; Station-B; Station-C; Station-D
Train-Y : Goes Via Station-B; Station-X; Station-D; Station-Y
How would I go about putting this information in a database so that if a passenger inquired about What trains start as Station-B? and What trains End as Station-D? then both Train-X and Train-Y should come in the result.

I would say you need to have three tables to make this work.
Station: station ID, name, etc.
Service: service ID, operator, number of train cars perhaps, etc.
Service_Stop: service ID, stop number, station ID.
You can then find services that stop at Station-B and subsequently at Station-D using a query something like the following:
SELECT
Service_ID
FROM
Station AS Start_Station
JOIN Service_Stop AS Start_Stop ON
Start_Station.Station_ID = Start_Stop.Station_ID
JOIN Service_Stop AS End_Stop ON
Start_Stop.Service_ID = End_Stop.Service_ID AND
Start_Stop.Stop_Number < End_Stop.Stop_Number
JOIN Station AS End_Station ON
End_Stop.Station_ID = End_Station.Station_ID AND
End_Station.Name = "Station-D"
WHERE
Start_Station.Name = 'Station-B'

I would use five tables:.
Train: train_id, name # e.g "The UnionT522"
Station: station_id, name # e.g. "Eggles Place"
Route: route_id, route_name # e.g. "Afternoon special at 4pm"
RouteStation: route_station_id, route_id, station_id, route_order, begin_flag, end_flag
TrainRoute: train_route_id, train_id, route_id # e.g. which train (above) is going on which route (above).
So RouteStation would have whether things began or ended at a given station for a given route.
TrainRoute would have information about which route a train is taking.

Related

How to fetch GPS coordinates of world's largest cities from WikiData via SPARQL, so that the result set includes Paris?

By searching on Google and SO, I came up with the following SPARQL query for finding world's largest cities for the purpose of rudimentary geocoding:
SELECT ?city ?cityLabel ?countryLabel ?iso ?population ?gps
WHERE {
?city wdt:P31 wd:Q515 . hint:Prior hint:runFirst true .
?city wdt:P17 ?country .
?country wdt:P297 ?iso .
?city wdt:P625 ?gps .
?city wdt:P1082 ?population .
FILTER (?population > 100000) .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
LIMIT 5000
https://query.wikidata.org/#SELECT%20%3Fcity%20%3FcityLabel%20%3FcountryLabel%20%3Fiso%20%3Fpopulation%20%3Fgps%0AWHERE%20%7B%0A%20%20%3Fcity%20wdt%3AP31%20wd%3AQ515%20.%20hint%3APrior%20hint%3ArunFirst%20true%20.%0A%20%20%3Fcity%20wdt%3AP17%20%3Fcountry%20.%0A%20%20%3Fcountry%20wdt%3AP297%20%3Fiso%20.%0A%20%20%3Fcity%20wdt%3AP625%20%3Fgps%20.%0A%20%20%3Fcity%20wdt%3AP1082%20%3Fpopulation%20.%0A%20%20FILTER%20(%3Fpopulation%20%3E%20100000)%20.%0A%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%7D%0AORDER%20BY%20DESC(%3Fpopulation)%0ALIMIT%205000
For some reason, the result set does not include Paris (France) but includes smaller cities in France. What am I doing wrong?
Thank you!
?city wdt:P31 wd:Q515 .
This triple pattern excludes Paris (Q90), because it’s not an instance of city (Q515).
It’s an instance of subclasses of city (Q515), though. For example: capital city (Q5119).
To find all items that are instances of city (Q515) or of a subclass of city (Q515), you can use a property path:
wdt:P31/wdt:P279*
P31: instance of
/: SequencePath
P279: subclass of
*: ZeroOrMorePath
As a city can be an instance of multiple city subclasses, you might want to make the results distinct, otherwise these cities will appear multiple times in the result:
SELECT DISTINCT ?city ?cityLabel #etc.

How do I add dynamic data to a database table?

I am trying to create a database for gym workout plans. This would have each member's workout plan, which comprises multiple exercises.
My question is: given that one member might have 5 exercises, another member 3, another 6, and so on, how can I store this in the database?
My thought process has been around hardcoding a set number of exercises in the table, and give the possibility of them being null (for exemple 10 exercises, but if you only use 5 exercises, everything else can be stored with nothing). But this doesn't feel very correct.
I am using MySQL for this.
Like #Sami pointed out, you are going to work on whats called a relational database.
Below is a simple database structure that will help you get started.
Members table
Table Name: tbl_members
Table Structure:
|member_id|member_name|member_contact|
Exercise or schedule table
Table Name: tbl_member_schedule
Table Structure:
|schedule_id|member_id|assigned_date|Schedule
In the tbl_member_schedule you can store the entire schedule as a JSON structure or you can further normalize. Since this is an example I am storing the entire schedule in JSON format inside the Schedule field.
Now when you want to retrieve the schedule of a specific member (member id: 1) you can query the database as follows:
select
tbl_members.member_id, tbl_members.member_name,
tbl_member_schedule.Schedule
from
tbl_members join
tbl_member_schedule on tbl_members.member_id = tbl_member_schedule.member_id
where
tbl_members.member_id = 1;
So you JSON structure for your schedule could be
{
day1: [
{exerciseName: 'dumbbell curls', reps: '8 x 4'},
{exerciseName: 'leg extension', reps: '8 x 3'}
],
day2: [
{exerciseName: 'dumbbell curls', reps: '8 x 4'},
{exerciseName: 'leg extension', reps: '8 x 3'}
]
}

SAP: join partner function data based on sales type

Working with SAP data, we are willing to enrich sales data with the last customer. Depending on the sales type, there are different partner function codes that correspond to the last company to which the sale is performed (e.g.: we may have indirect or direct sales). For now, we have been considering tables VBAP/VBAK/VBPA. We extract data from each table to separate files using sap4j, and then join VBAP and VBPA on VBELN, and consider partner codes WE (goods recipient) or custom consignation codes indicating the last buyer for consignations.
Is there some accurate way to know who is the last buyer in the chain for a given sale?
It can be done in the following way:
def sales_tabkey(row):
return "001{}{}".format(row['VBELN'], row['POSNR'])
def expected_partner_function_for_sales_type(row):
consignation_codes = set(['ORK', 'XKB', 'ZSOK', 'ZLZK', 'ZTSK', 'KE', 'ZED', 'ZZN'])
if row['AUART'] in consignation_codes:
return 'ZK'
return 'WE'
def get_kunnrf_frame(vbap, vbak, vbpa, kna):
consignation_codes = set(['ORK', 'XKB', 'ZSOK', 'ZLZK', 'ZTSK', 'KE', 'ZED', 'ZZN'])
df = pd.merge(vbap, vbak, on=['VBELN'], how='left')
df = pd.merge(df, vbpa, on='VBELN', how='left')
df["EXPPARVW"]=df.apply(expected_partner_function_for_sales_type, axis=1)
# KUNNR in kna is considered end_client_id
df = pd.merge(df, kna, on='ADRNR', how='left')[['VBELN','POSNR', 'KUNNR','end_client_id', 'ADRNR', 'PARVW', 'EXPPARVW', 'AUART']].drop_duplicates()
df['TABKEY']=df.apply(sales_tabkey,axis=1)
endclient_tabkeys = set(df.TABKEY.unique())
dfa = df[df.PARVW==df['EXPPARVW']]
dfb = df[df.TABKEY.isin(endclient_tabkeys.difference(set(dfa.TABKEY.unique())))]
return pd.concat([dfa, dfb])

Uitableview, json and detail tableview

I am asking a very simple question for someone who has encountered this kind of problem, please don't mark it down because there are many approaches to a solution.
I have a database which has cities and town, cities has many town, therefore, using one query displays many cities to correspond to the town. The result is as follows from mysql;
{City - town 1, town2, town 3} therefore if I want to display both the town and cities, I will end up with {city-town1, city-town2, city-town3}
I want to be able to compile all towns under a city, so that I can eventually use this source of array for my drilldown table, i.e on the first table; I want a list of non-repeating cities, on detail table, a list of all towns under that city. I only want to use one table and make the array dynamic such that I can add cities and towns without any problems (I have seen examples proposing different tables for different arrays)
I used this for- loop to iterate through mysql result
for (int i=0; i<json.count; i++)
{
ids= [[json objectAtIndex:i] objectForKey:#"Id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName = [[json objectAtIndex:i] objectForKey:#"townName"];
}
This gives me a list of cities but they are repeating;
I have been thinking about different approaches;
1)use #distinctunion- (Key-Value Coding)
2)use two jsons (one for city and another for towns) -compile arrays under each then join them using common id
3)use an iteration, iterate as shown above, but also search for similar cityNames and group towns under cities
Has anyone encountered a similar situation? what did you do? could you give an example if possible please
This is JSON Result for NSMutable Array of the above iteration
2013-09-18 07:50:52.025 JSONDATA[7119:11603] (
Bath,
"Bath, Somerset"
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
"Bath, Somerset"
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
Keynsham
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
Keynsham
)

Play 2.0 Complex join query how to parse (Anorm )

I am writing website using play 2.0 framework. And I have a problem when parsing results.
This request to mysql db gets all the links(can be several per episode) added to the database per episode together with all the information about episode and anime.
def lastReleasedLink(limit:Long=5):List[(((Episode,Anime),Link),Genre)] = {
DB.withConnection { implicit c =>
SQL(
"""
select * from yas_episodes as a
inner join anime as b on a.ep_anime_id=b.id
left outer join yas_links as c on a.ep_id=c.ep_id
LEFT JOIN yas_animes_genres AS d ON a.ep_anime_id = d.ag_anime_id
INNER JOIN yas_genres AS e ON e.g_id = d.ag_genre_id
where c.ep_id IS NOT NULL group by c.ep_id order by c.date desc limit {limit}
""").on('limit ->limit)as(Episode.simple~Anime.simple~Link.simple~Genre.simple map{
case episode~anime~link~genre => episode -> anime -> link -> Genre
} *)
}
}
The return value is type of List[(((Episode,Anime),Link),Genre)]
but how can I form output to the list of
let say List[episode,anime,Seq[links]] or List[episode,anime,Seq[Genres],Seq[links]] don't know where to put genres.
You can imagine that when you have two links per one episode information from table anime and yas_episodes will be copied for every row. So I need somehow stack them together(group) by episode record. Then it will be possible to iterate list and access to all objects.
As you can see, in the request there is many-to-many relation of anime with genres.
I have no idea how can I put all together to one list to be able to access it in view. Should Genre be part of Anime model?
It seems that the preferred way to achieve this is using the Scala collection API, see this post by Guillaume Bort.
In your case, I think you could do something like
lastReleasedLink groupBy { case (((e, a), l), g) => (e, a) }
to group by (Episode, Anime). Generally speaking, those manipulations are probably a little easier if you change your function to return a List[(Episode, Anime, Link, Genre)], i.e.
case episode~anime~link~genre => (episode, anime, link, genre)
then you could achieve the same with this code:
lastReleasedLink groupBy ((_._1, _._2))