简体   繁体   中英

SQL - Joining two tables

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. **

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();

?>

try this and for learning joins see here

SELECT c.* , u.*
FROM comments c
     INNER JOIN users u
         ON c.user_id = u.user_id
WHERE item_id = '{$item_id}' 
      AND review > '' 
ORDER BY good DESC, rate_id ASC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM