简体   繁体   中英

Mysql inner join/ multiple selects in one query?

Hi all!

I'm scripting a guestbook (personalized for each user). I have one table for users and a different one for the guestbook. Now, the way I'm currently displaying the name of the author of a post is not optimal. I simply have a row in the DB for "fromname" ie the authors name. I would like to select the authors name based on the authors ID and matching that to their name in the "users" table.

So... This is my mysql query right now:

$sql = " SELECT 
             pid,toid,fromid,message,fromname,name,pdate,flag 
         FROM gbook INNER JOIN users 
         ON id='{$_GET['id']}' 
         WHERE toid='{$_GET['id']}' 
         ORDER BY pdate DESC";

I guess I need to like... Select the name on a different condition but in the same query. But I don't know how.

I hope you understand my problem. Help will be greatly appreciated!

/Jafool

Assuming your users table has a column called username , the following should do what you want:

SELECT 
    pid,
    toid,
    fromid,
    message,
    u.username, 
    name,
    pdate,
    flag 
FROM gbook INNER JOIN users u
  ON id='{$_GET['id']}' 
WHERE toid='{$_GET['id']}' 
ORDER BY pdate DESC"

All I did was alias the user table (as u), and refered to u.username instead of the fromname you had before.

From what I am seeing it looks like you need to link to the users table twice since you have a fromid and a toid . If you have a users table, why would you have a fromname field in the gbook table? Anyway if my assumption is correct then you may be interested in the following query:

SELECT g.*, u1.username AS ToUser, u2.username AS FromUser
  FROM gbook AS g
  INNER JOIN users AS u1 ON u1.id = g.toid
  INNER JOIN users AS u2 ON u2.id = g.fromid
WHERE g.toid = '{$_GET['id']}' 
ORDER BY g.pdate DESC

Hard coding the name in the guestbook table is indeed dirty. Assuming your table structure is something like this:

users( id, name ) gbook( pid, toid, fromid, message, fromname, name, pdate, flag )

your query is already almost ok. Just change it as follows to select all columns of both tables:

$sql = " SELECT *
         FROM gbook g INNER JOIN users u
         ON u.id=g.fromid 
         WHERE toid='{$_GET['id']}' 
         ORDER BY pdate DESC";

Then you can display the name with something like

$result = mysql_query($sql);
while( $val = mysql_fetch_array($result) )
{ 
  $username = $val["u.name"];
}

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