一个查询而不是两个?

时间:2010-12-22 22:51:26

标签: php mysql

这里我用PHP进行了两次查询。有更简单的事情吗?一个查询而不是两个?

$id = mysql_real_escape_string($_GET["id"]);
$result = mysql_query("SELECT * FROM questionstable WHERE id=$id");
$row = mysql_fetch_assoc($result);
$category = $row['category'];
$main = mysql_query("SELECT name FROM categorytable WHERE id=$category");

4 个答案:

答案 0 :(得分:6)

SELECT       questionstable.*, categorytable.name
FROM         questionstable
  INNER JOIN categorytable
  ON         categorytable.id = questionstable.category
WHERE        questionstable.id=$id

顺便说一句,假设您的questionstable.id是数字,您可以使用$id = (int)$_GET["id"]并保存一些写作。 (它也可能是一个更安全的赌注。仅仅因为它被转义并不意味着它完全安全 - 特别是当它不在引号内时[给你很多SQL注入的选项]。;-))

答案 1 :(得分:2)

请尝试:

SELECT name 
FROM categorytable 
WHERE id = (
              SELECT category 
              FROM questionstable 
              WHERE id = $id
           )

答案 2 :(得分:1)

$id = mysql_real_escape_string($_GET["id"]);
$main = mysql_query("SELECT c.name FROM categorytable c inner join questionstable q on c.category = q.category WHERE q.id = $id");

答案 3 :(得分:1)

请勿使用内连接使用左连接,如果找不到类别,则不会返回任何结果

SELECT    questionstable.*, categorytable.name
FROM      questionstable
LEFT JOIN categorytable
ON         categorytable.id = questionstable.category
WHERE      id=$id