Reputation: 15744
I am trying to grasp the topic of joining tables in SQL. I know there are multiple joins but not sure which to implement here:
Here is my SQL line in php:
$sql=mysql_query("
SELECT * FROM comments
WHERE item_id = '{$item_id}'
AND review > ''
ORDER BY good DESC, rate_id ASC");
This is what I want to join with: Another table called "users". *"users" and "comments" both have a column called "user_id" to join.* I want to associate those two to find the full "username" in the users table.
I know SELECT is not best practice; but for the sake of this demo, can you include that here? I also know MySQL injection possibilities to watch for. **
Upvotes: 0
Views: 111
Reputation: 263893
I'd recommend you to use the ANSI SQL-92
format rather than ANSI SQL-89
. Try this one:
SELECT a.* , b.*
FROM comments a
INNER JOIN users b
ON a.user_id = b.user_id
WHERE item_id = '{$item_id}' AND
review > ''
ORDER BY good DESC, rate_id ASC
Good Definition of JOINs
Read something here: INNER JOIN (ANSI SQL-89 vs ANSI SQL-92)
Additional Information:
Since you are using PHP for this, I'll also recommend to use PHP PDO Technology
an example for that is:
<?php
$stmt = $dbh->prepare("SELECT a.* , b.*
FROM comments a
INNER JOIN users b
ON a.user_id = b.user_id
WHERE item_id = ? AND
review > ?
ORDER BY good DESC, rate_id ASC");
$stmt->bindParam(1, $item_id);
$stmt->bindParam(2, '');
$stmt->execute();
?>
Upvotes: 2