Hey guys I'm looking to get information out of 2 tables to create a JTABLE with that information.
The tables I am look at are 'shipments' and 'customers'
Where shipments takes the form of
shipNumber | shipperID | destID | size | weight
and customers takes the form of
ID | lastName | firstName | street | city | state | zip
The shipperID and destID both refer to a customer ID.
I am trying to get the city/state information out of the customers table that corresponds to the shipperID and destID.
I have tried the following
query = "SELECT shipments.shipNumber, customers.city, customers.state, customers.city, customers.state FROM shipments, customers WHERE shipments.shipperID = customers.ID";
Realizing that the duplicate customers.city/customers.state is populating the same information twice.
As previously said, I am trying to get the shipper city/state and destination city/state.
I also tried
query = "SELECT shipments.shipNumber, customers.city, customers.state, customers.city, customers.state, shipments.size"
+ " FROM shipments"
+ " INNER JOIN customers ON customers.id = shipments.shipperID";
Where this gives the same information.
I am not sure how to reference the destID = customer.id
Thanks,
Mike
The usual trick is to join with the customers table twice, once for the shipper and once for the destination:
SELECT shipments.shipNumber,
shipper.city, shipper.state,
dest.city, dest.state,
shipments.size
FROM shipments
INNER JOIN customers shipper ON shipper.id = shipments.shipperID
INNER JOIN customers dest ON dest.id = shipments.destID
Related
I have two tables with a 1 to n relationship.
table hobbies has a foreign key to table users called "userid"
SELECT * FROM hobbies WHERE userid = 7
can have multiple results.
table users contains a list of user profile data and table hobbies contains a list of user hobbies. I want to print a list of profile info of multiple users with hobbies of each user. (hobbies concatenated into one String)
i currently have the following sql queries: (pseudocode):
ResultSet result = executeQuery("SELECT * FROM users;");
for each returned row: executeQuery("SELECT * FROM hobbies WHERE userid =" + result.getInt("ref"));
how do I get the SQL queries out of the loop to optimize performance with a big list of users?
I was trying to do a LEFT JOIN and then doing the WHERE ref= check in java instead of in SQL
problem is that I then get duplicate users and i only want to print one row for each user when processing the result set
also Im not sure if the JOIN is really an improvement in performance, because I have to process more rows.
table users
+--------+------+---------+--------+
| userid | name | country | telno |
+--------+------+---------+--------+
| 1 | John | USA | 123456 |
| 2 | Max | Germany | 345678 |
+--------+------+---------+--------+
+--------------+------------+
| userid |hobby |
+--------------+------------+
| 1 | football |
| 1 | basketball |
| 2 | TV |
| 2 | Music |
| 2 | football |
+--------------+------------+
example output:
John, USA, 123456, {football, basketball}
Max, Germany, 345678, {TV, Music, football}
This is most probably the fastest solution
SELECT name, country, telNo, GROUP_CONCAT(hobby)
FROM users u LEFT JOIN hobbies h ON u.id = h.userId
GROUP BY name, country, telNo
See https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat for formatting options.
It's only good for the final output, e.g., if your hobbies contain commas, you wont't be able to parse them uniquely.
You can try :
SELECT h.userid, h.allyouneed FROM hobbies h, users u WHERE h.userid =u.userid
and get the info in one query
"SELECT * FROM hobbies h join users u on h.userid = u.userid WHERE userid = ?"
preparedStatement.setInt(result.getInt("ref"));
You can then save all the hobbies to a list similar to the 'Book' example below.
public static List<String> selectAll() throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
// THE LIST OF BOOKS YOU WILL RETURN
List<String> books = new ArrayList<>();
String sql = "SELECT BOOK FROM BOOKs";
try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");){
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
String book= rs.getString ("BOOK");
// ADD BOOK TO THE LIST
books.add(book);
}
}
finally{
ps.close();
rs.close();
}
// RETURN LIST OF ALL BOOKS
return books;
}
SELECT u.userid,u.name,u.country GROUP_CONCAT(hobby SEPARATOR ',')
FROM hobbies as h join users as u on h.userid=u.userid
where h.userid = ? GROUP BY u.userid,u.name,u.country;
assumming you have relationship on hobbies to users. the query will concat the columns of hobby of the join tables, and there will be one unique user per row.
So i have a section in my database where i need to do a join the tables look like this...
______________ _______________
|Vehicle | |Car |
|--------------| |---------------|
|_id PK | |_id PK |
|Warehouse | |VehicleId FK |
|Location | |Make |
|VehicleKey | |Model |
|______________| |_______________|
The Car VehicleID Foreign key is from the Vehicle Primary key. What I want to return is a cursor for each vehicle.
Warehouse Location Make Model
I'm not sure how I would construct the SQLite statement, can anyone give me a hand?? So far I have this as my method to retrieve all of the vehicles
public Cursor getCars()
{
Cursor c = database.query("SELECT Vehicle.Warehouse, Vehicle.Location, Vehicle.VehicleKey, Car.Make," +
" Car.Make FROM Vehicle INNER JOIN Car" +
"ON Vehicle Vehicle._id = Car.VehicleId",
null, null,null,null,null,null,null);
return c;
}
I'm pretty new to this way of doing database manipulation as I would normally have it done for me by a builder as I have only ever worked in c#. Can anyone help me out trying to get the correct results?
There is an error produced, but I think it's because of syntax of the sqlite statement
android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM SELECT Vehicle.Warehouse.........
There are no overloaded methods for query that accept a Sql String as a parameter.
See the documentation for the query methods here.:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
The first parameter is usually the table name.
The system is trying to build a Sql query using your whole query as the table name therefore you get a query such as "SELECT * FROM SELECT Vehicle..." etc
Either supply the correct parameters to the query method or use the rawQuery method which expects a standard Sql string.
String table = "Vehicle v INNER JOIN Car c ON Vehicle v._id = c.VehicleId";
String[] columns = new String[]{ "v.Warehouse", "v.Location", "v.VehicleKey", "c.Make"};
/*String where condition for example "where v.id = 1" 3rd parameter is your where codition in your db.query function */
/*db.query with where condtion : Cursor c = db.query(table,columns,"where v.id = 1",null,null,null,null,null);*/
Cursor c = db.query(table,columns,null,null,null,null,null,null);
Please review your query since i don't see patient Table in your join
You may edit your query using this syntax :
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
I have two db tables:
TARGET_TABLE (composite key on USER_ID and TARGET_ID)
USER_ID | TICKET_NO | TARGET_USER
---------------------------------
A11 | 12345 | A22
A11 | 12346 | A33
A44 | 12347 | A55
USER_DETAILS_TABLE
CORP_ID | USER_NAME
------------------
A11 | Steve
A22 | Jon
A33 | Paul
A44 | Dave
A55 | James
I want to be able to join these tables when I'm using select statements only.
For example I would like to do:
Select USER_ID, USER_NAME, TICKET_NO FROM TARGET_TABLE INNER JOIN USER_DETAILS ON TARGET_TABLE.USER_ID = USER_DETAILS_TABLE.CORP_ID
I can't seem to find the best way to do this. I have looked at the Hibernate examples for mapping but these are examples on how to write to both tables I simply want to get a user name from a table I can't touch!
I currently have two separate mappings for each table and run a separate query to get the user name but this doesn't seem like the best way to do it.
This HQL would work select tt.userId, tt.ticketNo, u.userName from TargetTable tt, User u where tt.userId = u.corpId.
However, this would return a List<Object[]> where each list element represents one row with 3 columns. You could extract these manually, or for example have some my.package.UserVO object with constructor public UserVO(String userId, String ticketNo, String userName) { ... }. In that case, this
session.createQuery("select new my.package.UserVO(tt.userId, tt.ticketNo, u.userName) from TargetTable tt, User u where tt.userId = u.corpId", UserVO.class).list()
would return instances of UserVO.
i doing some project using Java(netbeans sw) and link to Microsoft Access.
The problem occur when i need to inner join 3 tables together from Microsoft Access,
i have no problem to inner join 2 tables together
rsUpdate =
stmtUpdate.executeQuery("SELECT * FROM A_User Inner Join A_PC ON A_USER.SN = A_PC.SN");
which i able to get the result. But not inner join with 3 tables
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User Inner Join A_CPU ON A_USER.SN = A_CPU.SN , Inner Join A_Software ON A_CPU.SN = A_Software.SN")
For the SQL above I have 3 "A" table separately for USER | CPU | Software|
USER PK is SN | CPU FK is SN | Software PK is SN |
The Error I got java.sql.SQLException:Characters found after end SQL statement
Thanks
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User
Inner Join A_CPU ON A_USER.SN = A_CPU.SN
Inner Join A_Software ON A_CPU.SN = A_Software.SN");
no need for ',' here... try this above code
For Ms Access, when you JOIN more than table, the syntax is different. It should be this way:
SELECT *
FROM ((a_user
INNER JOIN a_cpu
ON a_user.sn = a_cpu.sn)
INNER JOIN a_software
ON a_cpu.sn = a_software.sn)
There should be no comma after the first join
rsUpdate =
stmtUpdate.executeQuery
("SELECT * FROM A_User Inner Join A_CPU ON A_USER.SN = A_CPU.SN Inner Join A_Software ON A_CPU.SN = A_Software.SN")
Problem Solved
For example -
Table A | Username(PK)| Address|
Table B | ID | Phone | Username(FK)|
Table C | SN | Brand | Model | Username(FK)
rs = st.executeQuery
("SELECT * FROM (A Inner Join B on A.Username = B.Username) Inner Join C on A.Username = C.Username");
if anyone looking for inner join 3 tables together by Using JAVA and Link to Access
use the referenece above.
Make sure you must link the table relationship in Access before run the java program if not it will pop out "ERROR IN ROW"
Thanks everyone who helping me :)
Suppose I have a MySQL table, and entity tag in hibernate, where a tag is a row in the following
id (primary key), tag, entity id
1, food, 77
2, shop, 98
3, food, 32
...
I'd like to return the total counts of the same tag sorted in decreasing number of entries. Aka,
tag, count
food, 2
shop, 1
...
I was told to do something like
SELECT tag, COUNT(*) `count`
FROM table1
GROUP BY tag
ORDER BY `count` DESC
Output:
| TAG | COUNT |
|------|-------|
| food | 2 |
| shop | 1 |
However, how do I read this newly created list of entities out from Hibernate? Do I need to somehow define a new object to read this list out?
The same question goes for say reading an entity (row) that is defined, but just joined with another entity as part of a query. How do I read out the result?
Thanks!
Query:
String query = "SELECT tag, COUNT(*) as count "+
"FROM table1 " +
"GROUP BY tag " +
"ORDER BY count DESC";
Additional class
public class Result
{
private String tag;
private int count;
// getters/ setters
}
Create native query
final Query nativeQuery = entityManager.createNativeQuery(query);
final SQLQuery sqlQuery = (SQLQuery) ((HibernateQuery) nativeQuery ).getHibernateQuery();
sqlQuery.addScalar("tag");
sqlQuery.addScalar("count");
sqlQuery.setResultTransformer(Transformers.aliasToBean(Result.class));