How to join three tables in SQLite? - java

How to join three tables in SQLite? I have three tables, one is Info, second is workForce and third is workDetails.
Table Info:id(PK),name,status,date,weather
Table WorkForce: id1(PK), subContractors,noOfPeople,noOfHours
Table WorkDetails:id2(PK),project,workDescription,TableInfo_id(FK) //contains multiple row
Table Info
ID NAME Weather Date Status
---------- ---------- ---------- ---------- ----------
1 Paul Sunny 15/10 MC
2 Allen Rainy 15/10 Working
Table WorkForce
ID1 SubContractors NoOfPeople NoOfHours
---------- -------------- ---------- ----------
1 AAA 2 2
2 BBB 3 1
Table WorkDetails
ID2 Project WorkDescription TableInfo_id
---------- ---------- -------------- ----------
1 A B 1
2 1
3 1
4 1
5 C D 2
6 2
7 2
8 2
Assume the name is Paul, so all the row with ID 1 and TableInfo_id 1 will be retrieved.
Here is what I tried so far
public Cursor readEntry(String name) {
String selectQuery = ("SELECT Weather,Date,Status,SubContractors,NumberOfPeople,NumberOfHours,TimeIn,TimeOut FROM "+TABLE_INFO+TABLE_WORKFORCE+TABLE_WORKDETAILS+ "WHERE Name= ? AND"+ID=ID1+ "AND"+ID=TableInfo_id);
Cursor c = database.query(TABLE_INFO,TABLE_WORKFORCE,TABLE_WORKDETAILS,new String[]{id,name,weather,date,status,iD1,subcontractors,numberOfPerson,numberOfHours,id2project,workDescription,TableInfo_id},MyDatabaseHelper.Name+"=?",
new String[] { String.valueOf(name)}, null, null, null, null,null,null,null,null,null,null,null,null);
if (c != null) {
c.moveToFirst();
}
return c;
}
My code seems like not working..how can I achieve this? Thanks!

Fist thing you need to do is to add foreign key of Table Info into Table WorkForce and foreign key of Table WorkForce into Table WorkDetails
Then write modify your query like this
Select * from Table Info tf
LEFT JOIN Table WorkForce twf ON twf.tf_id = tf.id
LEFT JOIN Table WorkDetails twd ON twd.tw_id = twf.id
Modify your query based on requirement after joining the three tables.
Check out the tutorials for adding a foreign key.

Add a foreign key to the workforce table the point to ID within the info table
select * from Info inner join Workforce inner join Workdetails ON Info.ID = Wordforce.SOME_FOREIGN_KEY AND Info.ID = Workdetails.TableInfo_id Where NAME = 'Paul'
Think that should work have not tried it tho

Related

How to select different data of the same table that depends on variable

I need to select some data from a join table. The thing is that this table changes its data depending on a variable x (if x=1 the data is A and if x=2 the data is B)
I am trying something like this:
"SELECT new nameDTO(joinTableA.dataA, joinTableB.dataB, table.something, table....) "
+ "FROM Table table "
+ "JOIN joinTable joinTableA"
+ "JOIN joinTable joinTableB "
+ "WHERE joinTableA.x = 1 AND joinTableA.x = 2"
+ "AND ..... "
However this WHERE does not work because the query returns nothing instead of de data of both cases.
I hope the question in understandable, it's a bit tricky.
There's a bit of information missing in your question, so I've made some up and hoping this is close enough to what you are trying to do.
I start with two tables. I'm only showing the content of the tables, not the definition.
table1
id content
-------------
1 Hello
2 World
table2
table1_id x content_a content_b
--------------------------------------
1 1 Content 1 Content 2
1 2 Content 3 Content 4
2 1 Content 5 Content 6
2 2 Content 7 Content 8
With the following SQL statement
SELECT
t1.content `greeting`,
CASE
WHEN t2.x = 1 THEN t2.content_a
WHEN t2.x = 2 THEN t2.content_b
ELSE "Unknown x value"
END `content`
FROM
table1 `t1`
INNER JOIN table2 `t2` ON t2.table1_id = t1.id
;
the result would be
greeting content
----------------------
Hello Content 1
Hello Content 4
World Content 5
World Content 8
This should be possible to convert to a JPQL query or a Criteria query.

how to extract source table using sql?

I'm trying to write a query that extracts and transforms data from a table and then insert those data into target table and that whole table data should be in single column in target table.below is the query i wrote
INSERT INTO Table2(column1) VALUES
(SELECT * FROM Table1);
table 1
id | ename | email | country |
1 d .. ..
2 v .. ..
3 s .. ..
4 n .. ..
in table2
src_data | src_column | src_tablename
1 eid
2 eid
3 eid
4 eid
d ename
v ename
s ename
n ename
email1 email
email2 email
email3 email
email4 email
country1 country
country2 country
country3 country
country4 country
how can i achieve this ...can you plz suggest me to get this
This:
INSERT INTO table2
SELECT id, 'id', 'table1' FROM table1
UNION SELECT ename, 'ename', 'table1' FROM table1
UNION SELECT email, 'email', 'table1' FROM table1
UNION SELECT country, 'country', 'table1' FROM table1
uses hardcoded names of the columns and the table.

From SQL to HQL

I'm having problems with the following query from SQL to Hibernate HQL:
select
(lot of things from table 1)
from
table1
inner join
table2 on table1.investigationEvent = table2.id_investigationEvent
inner join
table3 on table2.eventSection = table3.sectionEventsCod
inner join
table4 on table3.sectionEventsCod = table4.investigationSectionEvent
In HQL I wrote this:
Select blabla
+ "FROM table1 t1 "
+ "INNER JOIN t1.investigationEvent t2 "
+ "INNER JOIN t2.eventSection t3 , "
+ "table4 t4
INNER JOIN t4.investigationSectionEvent t3 "
+ "WHERE iset.typology.idTypology = :idTypology "
+ "WHERE ast.typology.idTypology = :idTypology ";
The problem is that with this syntax i can make joins from:
table 1 - > table 2
table 2 - > table 3
but i can't make the join
table 3 -> table 4
since the table 3 bean doesen't have any attribute to go to table 4 bean. However, is possibile make the contrary:
table 4 - > table 3 (since table 4 contains an attribute table 3 bean)
The problem is: using this syntax i have to call a second FROM (table4, as you can see from my hql query). Can you solve my problem? I have to make the query calling only the first table with FROM then using all JOIN(s).
This is Some Beans:
Table 1 {
...
Table 2 investigationEvent; }
Table 2 {
...
Table 3 eventSection
and then
Table 4{
...
Table3 investigationSectionEvent; }
The problem is that Table 3 doesen't contain Table 4.

SQL query Inner joins returns multiple rows

We have got 2 tables; table1, table2.
table1:
CNTY | ZIP | SERVICE
111 | 1234 | N
111 | | Y
112 | | Y
table2:
CNTY | ZIP |
111 | 1234 |
111 | 4321 |
112 | 4433 |
We are using oracle and trying the below query -
SELECT t1.SERVICE
FROM table1 t1
WHERE t1.CNTY IN (SELECT t2.CNTY
FROM table2 t2
WHERE t2.ZIP = '4433')
which return Y which is expected behavior. but if we send the t2.zip='4321' it is returning 2 rows, but we are expecting one row (Y). Also, if we send t2.zip='1234' which should return 'N'. But, above query returns 2 rows.
I am very new database side. We tried, but could not get it in one single statement. Is there any way to get the expected behavior?
Basically what I am expecting from the query is -
It should always return the SERVICE value from table1. If it finds the ZIP in table1 it should return the SERVICE value for the matching zip.
If there is no matching ZIP in table1, then it should find the CNTY associated with the given zip in table2 and then taking that CNTY value from table2, it should find the SERVICE value in table1 for the matching CNTY and return the value.
For example: For the ZIP 4321 no matching entry in the table1, but in table2 4321 is associated with 111, so for 111 in table1 SERVICE value is Y. So, the query should return Y.
I'm not sure why you expect only one row. Let's examine what the query does:
SELECT t2.CNTY FROM table2 t2 WHERE t2.ZIP = '4321'
This returns a single value: 111, corresponding to the following row:
111 | 4321 |
So the complete query is equivalent to
SELECT t1.SERVICE FROM table1 t1 WHERE t1.CNTY IN (111)
And that returns the service of these 2 rows, since they both have their CNTY equal to 111:
111 | 1234 | N
111 | | Y
It returns two becuase you have two rows in table1 with the city 111
select t1.* from
table1 t1
join table2 t2 on t2.city = t1.city and (t2.zip = t1.zip or t2.zip is null)
Now you are joinig on both city and zip code or if no zip code.
This will just return one row but if there are two city rows with 111 and no zip code then it will return 2
(note: not tested this SQL - Ive done it from memory ;) )
Is there any way to get the expected behavior?
Yes, you could join the tables on both CNTY and ZIP.
SELECT t1.SERVICE
FROM table1 t1, table2 t2
WHERE t1.CNTY = t2.CNTY AND t1.ZIP = t2.ZIP
AND t2.ZIP = '1234'
However, the above still won't work for ZIP '4321'. For this, the join must be more complicated.
SELECT COALESCE(t1a.SERVICE, t1b.SERVICE) AS SERVICE
FROM table2 t2
LEFT JOIN table1 t1a ON t1a.CNTY = t2.CNTY AND t1a.ZIP = t2.ZIP
LEFT JOIN table1 t1b ON t1b.CNTY = t2.CNTY AND COALESCE(t1b.ZIP, '') = ''
WHERE t2.ZIP = '4321'
This second query will work for all cases.
select service from (
select row_number() over (order by t1.zip nulls last) rn, service
from table1 t1
join table2 t2 on t2.cnty = t1.cnty and (t2.zip = t1.zip or t1.zip is null)
where coalesce(t1.zip, t2.zip) = '1234')
where rn=1
row_number used to sort records if there are two rows from join, like for zip=1234.
Query worked correctly for every zip.
You can also use:
select
case
when exists (select 1 from table1 where zip='1234')
then
(select service from table1 where zip='1234')
else
(select service from table1 where zip is null
and cnty = (select cnty from table2 where zip='1234'))
end service
from dual
like here:
with zips as (select '1234' zip from dual
union select '4321' from dual
union select '4433' from dual
union select 'TEST' from dual)
select zips.zip,
case
when exists (select 1 from table1 where zip=zips.zip)
then
(select service from table1 where zip=zips.zip)
else
(select service from table1 where zip is null and cnty =
(select cnty from table2 where zip=zips.zip))
end service
from zips
zip service
1234 N
4321 Y
4433 Y
TEST null

Selecting a data from column

My table is as below
ID Name City
-----------------
1 abc Mumbai
2 def Delhi
3 xyz bangalore
I want to write a query as
String query= select Name from table where (?)
what should come in the where clause if I want to select city Delhi if the input is an ID?
You should frame it as ,
String query= "select City from table where ID=2";
The general syntax select (COLUMN 1 , COLUMN 2) from table where condition; also you can use * to select the entire row.
will return Delhi in the resultset. hope you are using jdbc
select Name from table where id=2;
or
select City from table where id=2;
Where id = IdInputVar
Should work

Categories