SQL - 如何在另一个表中使用选定的ID?

时间:2013-11-28 16:19:33

标签: php mysql sql

SQL TABLES:
user = ID,姓名,电子邮件..
hero = ID,名称,级别..
owner = userid,heroid

我有这两个问题:

$result = mysql_query("SELECT heroid FROM owner WHERE userid='$id'"); 
$heroid=mysql_fetch_row($result); 
$result2 = mysql_query("SELECT name FROM hero WHERE ID = 'heroid[0]'");

$heroname = mysql_fetch_row($result2);
echo "User $id has a character named $heroname[0]";
$heroname = mysql_fetch_row($result2); 
echo "User $id has a character named $heroname[0]";
..

这可以通过一个查询完成吗?

1 个答案:

答案 0 :(得分:3)

是。你可以这样做:

SELECT h.name
FROM hero h
INNER JOIN owner o ON o.heroid = h.id
WHERE o.userid = $id