如何按全名搜索客户?

时间:2019-05-03 12:37:56

标签: java mysql sql

我正在创建一种方法,其中用户可以按名字,姓氏或全名搜索客户。搜索栏仅显示按名字或姓氏显示的结果,但是当我尝试按全名搜索客户时,记录将不会显示。

这是我的代码:

<script src="..." />

3 个答案:

答案 0 :(得分:2)

您的查询应为:

Select * FROM `Customer`
WHERE `firstName` LIKE '%" + keyword + "%' OR `lastName` LIKE '%" + keyword + "%'"

答案 1 :(得分:0)

public int getMatchingCustomerRecords(String keyword) {
        int rows = 0;
        try {
            if (db.startTransaction()) {
                String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
                String sqlSearch = "";
                if (keyword != null) {

             String[] keywordArray=keyword.split(" ");


            if(keywordArray.length>1) {
             // matching full Name
                sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' AND lastName LIKE '%" + keywordArray[1].trim() + "%'";
            }else {
             // matching firstName or lastName
                sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' OR lastName LIKE '%" + keywordArray[0].trim() + "%'";
            }
             ps = db.getQueryStatement(sqlSearch);
         } else {
             ps = db.getQueryStatement(sql);
         }
                rs = ps.executeQuery();
                if (rs.next()) {
                    rows = rs.getInt("TOTAL");

                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return rows;
    }

答案 2 :(得分:-2)

public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
    if (db.startTransaction()) {
        String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
        String sqlSearch = "";
        if (keyword != null) {
            sqlSearch = sql + " WHERE LOCATE(firstName ,'" + keyword + "')>=0 AND LOCATE(lastName ,'" + keyword + "')>=0";
            ps = db.getQueryStatement(sqlSearch);
        } else {
            ps = db.getQueryStatement(sql);
        }

        rs = ps.executeQuery();
        if (rs.next()) {
            rows = rs.getInt("TOTAL");

        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return rows;

}