开发者

Using one query in another in JDBC programming

I understand how to do this on paper in SQL, but am having trouble implementing this in Java (this is the first time I am actually programming JDBC stuff)

For example, say my database consists of:

movie(code, title, publisher)

customer(custno, name)

borrowed(custno, code)

And I want to find the name of customers who borrowed every movie by pubisher ABC

string no_of_ABC_movies = "SELECT COUNT(publisher), publisher FROM movie, WHERE movie.publisher = 'ABC'";

string no_of_cust_ABC_movies = "SELECT COUNT(name), name FROM customer,开发者_如何学JAVA borrowed, movie, WHERE customer.custno = borrowed.custno AND borrowed.code = movie.code AND movie.publisher = 'ABC'";


String query = "SELECT name" +
                        " name FROM customer, borrowed, movie" +
                        " WHERE customer.custno = borrowed.custno AND" +
                        " borrowed.code = movie.code AND" +
                        " movie.publisher = 'ABC' AND" + " "
                         no_of_cust_ABC_movies + " = " + no_of_ABC_movies;

This isn't the exact database I am working with, but query will work and print out the names of people who borrowed movies from ABC without the last line, but says I have an error in SQL syntax with the last line so I guess I don't know how to use one query within another.


It depends on your DBMS, but every SQL variant I've seen requires parens around subqueries.

Try something like:

...

" movie.publisher = 'ABC' AND ("
no_of_cust_ABC_movies + ") = (" + no_of_ABC_movies + ")";


You have problem with double name field without being separated by a comma in your query.

If your code is exactly as listed above, you have compilation error just above the last line-missing + to concatenate strings.

If that's a typo below is my suggestion.

  1. Remove duplicate select (use only one name) or
  2. Separate names by a comma ( I don't see a point of selecting name twice though)

And your last line is wrong.. you can not compare two select queries that way.. Just add the required where clauses.

(You should read database joins first, and then solve your problem)


I like to get my queries working in the query browser or workbench, then copy them over to Java. It keeps it to one new thing at a time...


You're query actually starts with

 SELECT name name FROM customer ...

The name column is duplicated - maybe that the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜