SQL: Cross table with foreign keys to two different tables - android

I have three tables:
zip_code_data
|zipCodeId| primary key
|zipCode| indexed
|other columns...|
location_data
|locationDataId| primary key
|city| indexed
|other columns...|
x_data
|id| primary key
|zipCodeId| foreign key
|locationDataId| foreign key
My goal is to run a query for either zipcode or city, and get all of the data associated with it from the zip_code_data and location_data tables
For example, if a user searches for a zipcode, I want to pull back all of the data associated with that zipcode from both tables.
My first guess is to get the foreign keys first from the cross table (x_data, example below) and then use those to get the data from each respective table... Since i'm somewhat of a novice user I don't know the best way to do this.
SELECT x_data.zipCodeId, x_data.locationDataId
FROM x_data
INNER JOIN zip_code_data
ON x_data.zipCodeId=zip_code_data.zipCodeId
WHERE zip_code_data.zipCode LIKE '2322%'

You could create an inline view:
select zips.othercolumn, LOCS.city
from zips
inner join x_data on zips.zip = x_data_zip and zips.zip like .....
left join (
select id, locations.city from locations
where locations.id = x_data.locationid
) as LOCS
or just join the locations table:
left join locations as locs on locs.locationid = x_data.locationid

I was about to post:
SELECT zip.*,loc.*
FROM x_data xref
JOIN zip_code_data zip ON zip.zipCodeId=xref.zipCodeID
JOIN location_Data loc ON loc.locationDataID=xRef.locationDataID
WHERE zip.zipCode LIKE '2322%' or loc.city LIKE '%aaa%'
but it looks like you've already got it...

Related

Database tool for Android other than SQLite?

I am new to Android programming and I have made a few simple apps which use SQLite to store user's data. Now I am working on a little more complex app in which I need to implement many-to-many relationship among the tables.
So basically, I have three layers (3 Tables) that would be connected to each other and I can't find a good tutorial or any documentation on how to do it. I've spent weeks on researching this. I also looked into realm-database but it's complicated for many-to-many table setup.
So is there any easier solution to this for a beginner? Or is there another tool that I can use to accomplish my task. Any suggestions would be helpful. Thank you :)
Your example isn't a many to many relationship. It's a one to many, each country can only exist in one continent and each state in only one country.
You can get the structure you want by adding a reference to the parent type's ID.
CREATE TABLE continent (
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
)
CREATE TABLE country (
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
continentId INTEGER NOT NULL,
name TEXT NOT NULL,
FOREIGN KEY continentId REFERENCES continent(_id)
)
CREATE TABLE state (
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
countryId INTEGER NOT NULL,
name TEXT NOT NULL,
FOREIGN KEY countryId REFERENCES country(_id)
)
To select all the countries on a continent, just ask SQL using the correct ID.
SELECT *
FROM country
WHERE continentId = ?
Or you can join them together.
SELECT *
FROM continent
JOIN country ON continent._id = country.continent
JOIN state ON country._id = state.countryId
You can do many-to-may relationships with SQLite. For the example shown you just need some XREF tables. For example (pseudocode):
Table CONTINENT(
ContinentID
,ContinentName
)
Table COUNTRY(
CountryID
,CountryName
)
Table CONTINENT_COUNTRY_XREF (
Continent_Country_XrefID
,ContinentID
,CountryID
)
Hope this helps.
Yes you can use Ultralite database from SAP. It supports joins as well.
More details here
http://scn.sap.com/community/developer-center/mobility-platform/blog/2012/08/23/how-to-open-an-ultralite-db-udb
To connect two tables in a many to many relationship, create a third table with three columns. The first column is just a standard is for the primary key. The other two columns are secondary keys into the two original tables. Googling " many to many relationship" will provide more details.

SQL: Table with match-results needs team information added, based on team-ids. How do I do this for home and away-teams in one query?

I am programming on Android and only starting with SQL:
What I have are 2 SQL tables, table A contains a list of match-results of sports games, table B contains all information about the teams.
Table A has two team-ids, one for the home-team, one for the away-team.
I want to create a sql query, that gets a match-result for every match, that is linked up to the corresponding teams, e.g. the two team-ids in table A should get replaced by at least the team-name (preferably more columns) of table B.
So in short: For every match in table A -> get all match-info from table A -> add information for the home and the away team from table B, corresponding to home-id and away-id from table A -> deliver result
I achieved this party through an SQL JOIN, but I only managed to join the information for either the home- or the away-team, not both, since the columns get in conflict, since both the home and away team information come from the same table and thus the column names are the same (home team has "team_name", and away team also has "team_name" -> conflict)
How can I achieve this?
For some information on why I would like to do this in one query: I am working on Android, displaying a list of match-results, which are loaded asynchronously via a Loader, which feeds a Cursor to a CursorAdapter. As I understand the cursor, it's its nature to only deliver one result per row of the list, thus all the data querying has to be done in one sql query.
Thank you for your help!
EDIT: My current sql join is this
ScheduleTable.TABLE_SCHEDULE + " JOIN " + TeamsTable.TABLE_TEAMS + " ON " +
ScheduleTable.TABLE_SCHEDULE+"."+ScheduleTable.COLUMN_HOME_TEAM_ID + " = " + TeamsTable.TABLE_TEAMS+"."+TeamsTable.COLUMN_ID
The easiest way to look up a value from another table might be a subquery:
SELECT Date,
Result,
(SELECT Name FROM Teams WHERE ID = Schedule.HomeTeamID
) AS HomeTeamName,
(SELECT Name FROM Teams WHERE ID = Schedule.AwayTeamID
) AS AwayTeamName
FROM Schedule
However, this becomes unwieldy if you need to look up more than one column for a team.
To be able to address a single table that you are using multiple times in the same FROM clause, you must use table aliases:
SELECT Schedule.Date,
Schedule.Result,
HomeTeam.Name,
AwayTeam.Name
FROM Schedule
JOIN Teams AS HomeTeam ON Schedule.HomeTeamID = HomeTeam.ID
JOIN Teams AS AwayTeam ON Schedule.AwayTeamID = AwayTeam.ID

I want to get data from two tables.my query is giving data but WHERE clouse is not giving me data which i want

i have two tables DISCIPLINE and SUBJECT.
DISCIPLINE table has _DISCIPLINE_ID as a primary key and a DISCIPLINE_Name column.
SUBJECT table has _SUBJECT_ID as a primary key SUBJECT_Name and DISCIPLINE as a Forign key.
i want to select Subject from SUBJECT table Who has the same _DISCIPLINE_ID in the DISCIPLINE table.
here is my query:
SELECT DISCIPLINE._DISCIPLINE_ID,
SUBJECT.SUBJECT_Name
FROM DISCIPLINE,
SUBJECT
WHERE SUBJECT.DISCIPLINE = DISCIPLINE._DISCIPLINE_ID
it gives me data but it selects all the Subjects and DISCIPLINE.
i think it is how your from clause is built, have you tried inner join instead of a comma seperating the table selections?

Automatically Create Insert Statements to Fill Junction Table in a Pre-Created DB

For a simple android app I'm creating as a teaching tool for myself (for using relational dbs/SQL among other things - pardon the simplicity of the question if you will). I'm pre-creating a sqlite db to ship with the application. I'm doing this based on the following SO question.
I've got two tables with a many to many relationship and a junction table to define those relationships as follows:
CREATE TABLE Names (_id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE Categories (_id INTEGER PRIMARY KEY,
category TEXT
);
CREATE TABLE Name_Category (name_id INTEGER,
category_id INTEGER,
PRIMARY KEY (name_id, category_id),
foreign key (name_id) references Names(_id),
foreign key (category_id) references Categories(_id)
);
I've got sets of insert statements to fill the Names and Categories tables. I'm now faced with the task of filling the junction table. I'm sure that I could create the insert statements by hand by looking up the ids of the names and categories that I want to match, but that seems a bit silly.
In order to automatically create the insert statements for the junction table, I imagine that I could create a script based on a set of name and category pairs that will search for the appropriate ids and dump an insert statement. (I came up with this as I was asking the question and will research it. Don't you love it when that happens?)
Does anybody have any suggestions for ways to do this?
EDIT I added the foreign keys because, as pointed out below, they'll help maintain integrity between the tables.
EDIT #2 To solve this, I created a simple Perl script that would take a text file with name - category pairs and dump them out into another file with the appropriate SQL statements.
The name - category text file has a format as follows:
'Name' 'Category'
The Perl script looks like this:
use strict;
use warnings;
open (my $name_category_pair_file, "<", "name_category.txt") or die "Can't open name_category.txt: $!";
open (my $output_sql_file, ">", "load_name_category_junction_table.sqlite") or die "Can't open load_name_category_junction_table.sqlite: $!";
while (<$name_category_pair_file>) {
if (/('[a-zA-Z ]*') ('[a-zA-Z ]*')/) {
my $sql_statement = "INSERT INTO Name_Category VALUES (
(SELECT _id FROM Names WHERE name = $1),
(SELECT _id FROM Categories WHERE category = $2))\;\n\n";
print $output_sql_file $sql_statement;
}
}
close $name_category_pair_file or die "$name_category_pair_file: $!";
close $output_sql_file or die "$output_sql_file: $!";
You can use this insert in your script or code (replacing the strings or using ?):
insert into Name_Category values(
(select _id from Categories where category='CAT1'),
(select _id from Names where name='NAME1'));
Also, you can alter the Name_Category table to constraint on the values that can be inserted and/or deleted:
CREATE TABLE Name_Category ( name_id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (name_id, category_id),
foreign key (name_id) references Names(_id),
foreign key (category_id) references Categories(_id));
create two main tables first and then create a junction table in which primary key of both main tables will be available as foreign key.. Primary key of junction table will be union
of primary key of first and second main table.
Create trigger now to automatically insert into junction table...
Also don't forget to create table with cascade deletion and cascade updatation so that any value updated or deleted in main tables will be automatically reflected in junction table

SQLite-how to compare two column

friends,
I am doing an Android project in my company, still some small work is remaining, I need your help to complete the task.
The problem is...
I have created two tables in which, table1 has an empty column, for purpose for saving name...
The table2 has a list of names, the objective is only the names from this list should be should be saved in the table1's empty column other than that it shouldn't accept any of the name typed manually.
You appear to want to make the list of names a validation: if the user wishes to save a name to table1, the name must already exist in table2.
Typically this would be done as in the following example, in which only the products listed in PRIZEPRODUCTS can be entered into PRIZEWINNERS table: someone could not win a Boat, for example, given the data below:
PRIZEPRODUCTS
id
productname
1|TV
2|iPad
3|backpack
PRIZEWINNERS
id
productid
winner
ALTER TABLE PRIZEWINNERS
ADD CONSTRAINT PRIZEWINNERS_PRIZEPRODUCTS_FK
FOREIGN KEY(productid) REFERENCES PRIZEPRODUCTS(id)
SQLite doesn't create the foreign key using ALTER TABLE but as part of the create-table statement. See here for the syntax. For enabling foreign key support in Android (2.2), see here.
Now, you can establish the foreign key on the [productname] column if [productname] were the key of PRIZEPRODUCTS. In other words, you could make person-name the key of the table rather than having a PersonID. But if that name is changed in the validation table, it can break the foreign key relationship, unless ON UPDATE CASCADE is enabled, but I am not sure if this is supported in Android.
I hope below query will work for you.
insert into table1(name) values (select name from table2 where id=?).
Thanks.

Categories

Resources