tags:

views:

35

answers:

2

I need to create a join query for the following:

Table supplier:

  • id
  • name

Table supplier_vehicles

  • id
  • supplier_id
  • vehicle_id

A supplier can have multiple vehicles.

On my front-end form I have a checkbox list - a user can select multiple vehicles. The back end script needs to do a search and bring back all suppliers that contain any of the specified vehicle id's.

The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example):

Array
(
    [0] => 1
    [1] => 4
    [2] => 6
)

At the moment I could do with with some SQL examples so that I can test the query using different values.

+2  A: 

If you know the vehicle ID's, you can use an IN clause:

SELECT *
  FROM supplier s
     , supplier_vehicles v
 WHERE s.id = v.supplier_id
   AND v.vehicle_id IN (1, 4, 6)

If you just want the distinct supplier ID's, you could use DISTINCT.

SELECT DISTINCT s.supplier_id
  FROM supplier s
     , supplier_vehicles v
 WHERE s.id = v.supplier_id
   AND v.vehicle_id IN (1, 4, 6)
dcp
Need to use dynamic SQL for dynamic IN parameters...
OMG Ponies
@OMG Ponies - I was just trying to give him some query examples. I wasn't sure what language he was using on front end, so I tried to keep it general. But I wouldn't do a hardcoded query on the front end due to SQL injection risks, I'd make an SP and pass the values and use dynamic SQL on the back end if need be.
dcp
Preaching to the choir :) I don't know if dynamic IN parameters are what the OP needs.
OMG Ponies
@OMG Ponies - Yes, I've seen enough of your posts and respect you enough to know that you knew that :). I'm not sure if this is exactly what the OP needs either, I was just trying to show him how to do some simple JOIN queries and get distinct suppliers back for given vehicle IDs. Anyway, hopefully they'll clarify it if they need more detailed answers.
dcp
A: 

First create a string that holds all of the elements in your array separated by commas. Not sure what language you are doing this in but you can either use a JOIN function or loop through the array.

According to your example the string would be equal to 1,4,6

The for your SQL query :

"SELECT s.name
FROM supplier AS s
JOIN supplier_vehicles AS v
ON s.id = v.supplier_id
WHERE v.vehicle_id IN (" + stringName + ")"
Kyra