3

Hi I am trying to query a table in my database, basically I need to select the driver_id from the table where the team_id is the same as the users driver id, stored in a variable $user_driver_one. So pretty much selecting the other driver with the same team_id.

column driver_id 1 2 3 4 5 6 7 8 9 10

  column team_id 3 3 2 2 1 1 4 4 5 5

So the user could have $user_driver_one = 4, so I need to select in a query the driver_id = 3, as driver_id 3 has the same team_id.

I am having problems with this, any help is much appreciated.

3
  • I'm curious what is the relation between driver_id an team_id. Why do you want people that have the same id as their team ? Looks like a code smell. Commented Sep 29, 2011 at 12:14
  • basically the drivers all belong to a team, this is formula one. and the user selects 3 drivers, so in the query, I need to be able to select the teammate of the driver the user has selected. Commented Sep 29, 2011 at 12:17
  • I updated my answer after you edited your question. Cheers. Commented Sep 29, 2011 at 12:23

4 Answers 4

4

Make sure you escape the parameter

$user_driver_one = (int) $user_driver_one;

MySQL:

"SELECT `driver_id` 
 FROM `table` 
 WHERE `team_id` = (
     SELECT `team_id`
     FROM `table`
     WHERE `driver_id` = '$user_driver_one'
     LIMIT 1
    )
 AND `driver_id` != '$user_driver_one'";
Sign up to request clarification or add additional context in comments.

1 Comment

No problem! Take an hour or two to learn some Subquery and Join basics and you will feel so much more confident with SQL.
1
 SELECT driver_id FROM T1 WHERE team_id = driver_id AND team_id = @user_driver_one

Comments

0

If you're gonna use PHP it would look like this:

mysql_query("SELECT driver_id FROM tablename WHERE team_id = '$user_driver_one'");

Of course, some sanitation before doing a query would be smart, especially if you're assigning the $user_driver_one variable from a user input.

Comments

0
select driver_id from yourtablename where team_id in (select team_id from yourtablename where driver_id=4)and driver_id!=4

You can use $user_driver_one in place of 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.