views:

1025

answers:

3

Hello, I am attempting to return the number of customers located in a specific state that have rented a specific movie, where the rents table contains two columns, one for customer ID and one for the movie ID. The function takes in a movie ID and the state and returns an integer with the amount of customers.

Right now I have an implementation, but it counts up the amount of rows the entire query returns:

SELECT COUNT(*) as numCustomers FROM CUSTOMER C, RENTS R WHERE C.ST = '" + state + "' AND R.mid = " + movieID

And then I count the amount of rows. I would like to just be able to check numCustomers for the correct data. Thanks!

+8  A: 

Firstly, you are lacking a clause to link your RENTS table and your CUSTOMER table on CustomerId?

Secondly, you should use the INNER JOIN functionality in the FROM clause to add your two tables.

Thirdly, you should NOT build your sql as a string like this as you will be open to SQL Injection.

At a guess, the sort of SQL you may be after is as follows.

DECLARE @movieId int
DECLARE @state varchar(2)

SET @movieId = 12345
SET @state = 'NY'

SELECT
 COUNT(DISTINCT C.CustomerID) as numCustomers
FROM
 CUSTOMER C
INNER JOIN
 RENTS R
ON
 C.CustomerID = R.CustomerId
WHERE
 C.ST = @state
AND
 R.mid = @movieId
Robin Day
+1  A: 

Guessing something about your schema (how RENTS relates to CUSTOMER):

SELECT COUNT(*) as numCustomers
FROM CUSTOMER c
WHERE
    c.ST = @State
    AND EXISTS
    (
        SELECT *
        FROM RENTS r
        WHERE r.CustomerID = c.CustomerID
        AND r.mid = @movieID
    )

Also, you should research SQL injection attacks, if you're not already familiar with that subject.

Daniel Pratt
A: 

You have to connect your Customer and Rental tables otherwise you'll get an entry for every entry in each table.

How about: SELECT COUNT(C.ID) AS numCustomers FROM CUSTOMER C, RENTS R WHERE C.ID = R.RenterID AND C.ST = '" + state + "' AND R.mid = " + movieID

0bytes