简体   繁体   中英

Select data from two tables using SQL

I have two tables linked by another table like this:

ROLES(RoleID, RoleName)
EMPLOYEES(EmployeeID, E_Name, Address)
ROLE_EMPLOYEES(RoleID#,EmployeeID#).

I want a query that retrieves all from EMPLOYEES and RoleID from ROLES and displays on Java form.

I have tried this but does not work:

rs=st.executeQuery("SELECT EMPLOYEES.*, ROLES.* FROM EMPLOYEES JOIN ROLES");               

while(rs.next()){
    //MOVE THE CURSOR TO THE FIRST RECORD AND GET DATA
    int employeeid=rs.getInt("EmployeeID");
    String id=Integer.toString(employeeid);
    String name=rs.getString("E_Name");
    String addr=rs.getString("Address");
    String s = rs.getString("RoleID");
    jComboBox1.addItem(s.trim());

    //DISPLAY THE FIRST RECORD IN THE TEXT FIELD
    txtEmpNumber.setText(id);
    txtEmpName.setText(name);
    txtEmpAddress.setText(addr);
    jComboBox1.setSelectedItem(s);
}

You may try this:

SELECT
   EM.*, RL.*
FROM
   EMPLOYEES EM
INNER JOIN
   ROLE_EMPLOYEES REM ON REM.EmployeeID = EM.EmployeeID
INNER JOIN
   ROLES RL ON RL.RoleID = REM.RoleID

Just by writing the keyword JOIN the db-engine does not know in which way it should join the data of the tables; unless you want to retrieve a cartesian product (that's not your case), you need to explicitly set the criteria by using the ON clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM