Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concat sql query using union operator

Tags:

java

sql

mysql

jdbc

String Query="select * from recommendation.sports WHERE feed LIKE'%"+s1+"%'

    UNION "select * from recommendation.software  WHERE feed LIKE '%"+s1+"%'

    UNION "select * from recommendation.website   WHERE feed LIKE '%"+s1+"%'

    UNION "select * from recommendation.others    WHERE feed LIKE '%"+s1+"%'

    UNION "select * from recommendation.business  WHERE feed LIKE '%"+s1+"%'";
like image 290
Giri Avatar asked Jul 09 '26 09:07

Giri


2 Answers

maybe you mean this?

String Query = "select * from recommendation.sports WHERE feed LIKE '%" + s1 + "%' " +
                "UNION " +
                "select * from recommendation.software  WHERE feed LIKE '%" +s1+ "%' " +
                "UNION " +
                "select * from recommendation.website   WHERE feed LIKE '%" +s1+" %' " +
                "UNION " +
                "select * from recommendation.others    WHERE feed LIKE '%"+s1+"%' " +
                "UNION " +
                "select * from recommendation.business  WHERE feed LIKE '%" +s1+ "%'" ;

but I advise you to use PreparedStatements on the query to avoid SQL Injection.

String Query = "select * from recommendation.sports WHERE feed LIKE CONCAT('%', ?, '%') " +
                "UNION " +
                "select * from recommendation.software  WHERE feed LIKE CONCAT('%', ?, '%') " +
                "UNION " +
                "select * from recommendation.website   WHERE feed LIKE CONCAT('%', ?, '%') " +
                "UNION " +
                "select * from recommendation.others    WHERE feed LIKE CONCAT('%', ?, '%')  " +
                "UNION " +
                "select * from recommendation.business  WHERE feed LIKE CONCAT('%', ?, '%')" ;

PreparedStatement pstmt = con.prepareStatement(Query);
pstmt.setString(1, s1);
pstmt.setString(2, s1);
pstmt.setString(3, s1);
pstmt.setString(4, s1);
pstmt.setString(5, s1);
ResultSet _result = pstmt.executeQuery();
  • JAVA PreparedStatement
like image 79
John Woo Avatar answered Jul 12 '26 02:07

John Woo


Try This:

 String Query="select * from recommendation.sports WHERE feed LIKE'%"+s1+"%'

    UNION select * from recommendation.software  WHERE feed LIKE '%"+s1+"%'

    UNION select * from recommendation.website   WHERE feed LIKE '%"+s1+"%'

    UNION select * from recommendation.others    WHERE feed LIKE '%"+s1+"%'

    UNION select * from recommendation.business  WHERE feed LIKE '%"+s1+"%'";
like image 43
Hamlet Hakobyan Avatar answered Jul 12 '26 00:07

Hamlet Hakobyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!