Almahruqi
Almahruqi

Reputation: 1

getting wrong data when I use inner join keyword

I have a problem with MySQL query, I want to get all rows that associate with same FK. code is :

$idad =(int)$_GET['id'];// I am using this to get the id of ad from the url of page
$sql = 'SELECT * FROM ads INNER JOIN cars ON cars.ad_id="'.$idad.'"
                 INNER JOIN address ON address.ad_id="'.$idad.'" ';

I got the wrong result for ads table only , it returns the wrong ad_id row. But for address and cars I got the correct row.

Upvotes: 0

Views: 252

Answers (3)

PHP Geek
PHP Geek

Reputation: 4033

you are selecting all from ads table but you have to use join for that.

$idad =(int)$_GET['id'];
$sql = 'SELECT * FROM ads INNER JOIN cars ON cars.ad_id=address.ad_id
                 INNER JOIN address ON address.ad_id=ads.ad_id WHERE ad_id=$idad';

Upvotes: 0

Almahruqi
Almahruqi

Reputation: 1

I solved by editing the SQL query:

$sql = 'SELECT * FROM ads  JOIN cars ON cars.ad_id="'.$idad.'" AND ads.ad_id="'.$idad.'"
              JOIN address ON address.ad_id="'.$idad.'" ';

and it worked fine now.

Upvotes: 0

Ashu
Ashu

Reputation: 1320

You have to map the ad_id with other table forgin key ad id.

$sql = SELECT * FROM ads 
       INNER JOIN cars ON cars.ad_id=ads.ad_id
       INNER JOIN address ON address.ad_id=ads.ad_id
       WHERE ads.ad_id = $idad

Upvotes: 2

Related Questions