About creating SQL for search functions.

Asked 2 years ago, Updated 2 years ago, 47 views

Creating search functionality using Java and SQL.
The values entered in the search items (name, name, kana, hobby text box) on the form screen are filled in the placeholder specified in the where clause of the SQL statement, and the data obtained for the table is displayed on the screen as search results.
Search in the form of AND conditions as a specification, and search items are partial match searches.In addition, if there is no input for each search item (if it is empty), what SQL should I create if I do not specify that item to narrow down the record?I'm having trouble creating SQL.

java sql

2022-09-30 19:32

2 Answers

For each search item, use the OR operator to connect the conditions under which the input is empty and true in a partial match search.
If the input is empty, the search criteria are ignored, and only if the input is not empty, the partial match search is reflected.

For example, for the schema below,

CREATE TABLE Tbl
(col1VARCHAR(10) NOT NULL
, col2VARCHAR(10) NOT NULL
);

Queries for col1,col2 can be written using the parameters :1 through :4 as follows:
(Search input with parameter :1,:2 as col1.Search input with parameter :3,:4 is col2)

SELECT col1,col2
FROM Tbl
WHERE (NULLIF(:1,') IS NULL OR col1 LIKE('%'||:2|'%')
  AND (NULLIF(:3,') IS NULL OR col2 LIKE('%'|:4|'%')
ORDER BY COL1, COL2
;

Each RDBMS has a different description of the parameters, so please adjust it if it does not work as it is.
Example: MySQL Results


2022-09-30 19:32

As a precondition, the search value for the criteria is using PreparedStatement, and the flow of SQL statements specified there will be as follows.

Check the total number of conditions
Zero decision specification → No WHERE clause
One decision specification → Create a WHERE clause and enter conditions
There are two or more decisions → First, create a WHERE clause and enter conditions, and from the second
Add an AND condition.

Depending on how the input is received, the content of the code may change to for statement or access to array, but I think it would be good to consider the total number of conditions for assembly.


2022-09-30 19:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.