I have two MySql tables like the following:
Cat
------
id : INT NOT NULL PRIMARY KEY
name : VARCHAR(32)
Cheezburger
-------
id : INT NOT NULL PRIMARY KEY
catId : INT FOREIGN KEY REFERENCES Cat (id)
pattyCount : INT
When I perform a LEFT JOIN on the two tables using PHP’s PDO I’d do the following:
$database = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $pasword);
$query = $database->prepare('
SELECT * FROM Cat
LEFT JOIN Cheezebuger.id ON Cheezburger.catId = cat.id
WHERE Cat.id = ?');
$query->bindParam(1, $someId);
$query->execute();
$cat = $query-fetch();
My question is, how can I differentiate the id field associated with the Cat table and the id associated with the Cheezburger table? $cat['id'] is giving me the Cheezburger id field.
It’s often inadvisable to
SELECT *. Instead, be explicit about the columns you want and assign aliases to like-named columns:Now, to retrieve
Cat.id, use$cat['catid']and to retrieveCheezeburger.id, use$cat['chzid'].A strong reason against doing
SELECT *is that if you add more columns later which are not needed in this particular part of your application, you won’t be using extra memory on the database server to retrieve unneeded data and fetch it into the web application where it won’t be used. If you happened to add a binary BLOB column later, you could potentially pull over a lot more data unnecessarily.The other reason is the one you’ve discovered. You can invite ambiguity in column names.