Question: I'm having difficulty trying to find the best way to get my results from a table. I want to get the targeted row from a table by one using the primary key from another using a foreign key.

The tables are would be set similar to this(minus a lot of other attributes for space):

```
user Table:
  user_Id(pk)
  name
  type
  venue_Id(unique/indexed)

venue Table:
  venue_Id(fk)
  rating

```

Logic flow is: user\_Id is provided by a session variable. Query DB table 'user' to find that user. Go to type of user to identify if user is person or venue. Assuming user is venue, go to DB table 'venue' and query table for rating using foreign key from unique/indexed venue\_Id from user table.

The query looks like 

```
SELECT rating FROM `venue` WHERE `user_Id` = '$user_Id' AND `type` = 'venue'

```

Is this possible, and if so, what is the correct way to go about it?

Answer: 
You have a few ways to retrieve this information.

Using JOIN:

```
SELECT v.rating 
FROM venue v INNER JOIN user u
ON v.venue_id= u.venue_id 
AND u.`user_Id` = '$user_Id' AND u.`type` = 'venue'

```

Using an `IN` sub-query 

```
SELECT rating 
FROM venue 
WHERE venue_id IN (SELECT venue_id FROM user
   WHERE `user_Id` = '$user_Id' AND `type` = 'venue')

```

BTW, you should consider protect your code from [potential SQL Injections](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)
Its a bit unclear you explained that way.
From what I get, there is 2 table User and Venue.
In User table u have: user\_id, venue\_id, name, type.
While in Venue table u have: venue\_id, rating.

You are expecting to get rating (**Venue** Table) while you use the WHERE clause in user\_id and type which both stored on **User** Table.

Your Query:
SELECT rating FROM venue WHERE user\_Id = '$user\_Id' AND type = 'venue'

It is impossible to get it done like above because you are selecting from venue table while user\_id and type is not from venue table. So it will make it unidentified even you have chaining the FK. Because FK will only to show and make some constraint to parent child table. 

The query should be something like this:

SELECT rating FROM venue v JOIN user u on v.venue\_id = u.venue\_id WHERE u.user\_Id = '$user\_Id' AND u.type = 'venue'

Correct me if I am wrong..