从mysql中的相关表中选择值

时间:2013-01-03 15:36:39

标签: java mysql sql database

CREATE TABLE "Employer" (
        "employerID" INT PRIMARY KEY NOT NULL,
        "name" CHAR,
        "industry" CHAR,
        "contact1" CHAR,
        "contact2" CHAR,
        "email" CHAR,
        "website" CHAR,
        "facts" CHAR,
        "phone" VACHAR
        )

CREATE TABLE "Job" (
        "jobID" INT PRIMARY KEY NOT NULL,
        "employerID" INT,
        "title" CHAR,
        "description" CHAR,
        "type" CHAR,
        "salary" CHAR,
        "benefits" CHAR,
        "vacancies" INT,
        "closing" CHAR,
        "requirement" CHAR,
        "placement" BOOL,
        "applyTo" CHAR,
        "notes" CHAR,
        FOREIGN KEY (employerID) REFERENCES Employer(employerID)
        )

我正在寻找从数据库中获取值并将它们设置为JLabel文本,但我不确定涉及foreign键时的sql语句。 SQL语句应该SELECTJob以外的employerID表中的所有值,并使用外键employerID来获取公司的name ...可以anoyone告诉我这个正确的sql语句..我想显示如下例子的信息:

分析师 - MICROSOFT

JobID:4545454 说明:干得好 电子邮件:123@hotmail.com 电话:45545

但不确定如何显示MICROSOFT

public void setText() {
    try {
    String sql = "SELECT a.*, b.name FROM Employer a INNER JOIN `Job` b ON a.employerID = b.employerID";
    pst = conn.prepareStatement(sql); 
    rs = pst.executeQuery();
    while (rs.next()) {

        System.out.println(rs.getString(1)); //how Do i Print the name value from Employer table?? 
        System.out.println(rs.getString(2));
        System.out.println(rs.getString(3));
        System.out.println(rs.getString(4));
        System.out.println(rs.getString(5));
        System.out.println(rs.getString(6)); 
    }


}

如何从EMployer表中打印name值以及来自Job表的所有数据?

1 个答案:

答案 0 :(得分:1)

简单的联接可能会起到作用。

SELECT  a.*, b.*       // -- SELECT the columns you want to display
                       // -- eg b.Title
FROM    Employer a
        INNER JOIN `Job` b
            ON a.EmployerID = b.EmployerID