PHP,SQL新手帮助

PHP,SQL新手帮助,php,sql,mysql,Php,Sql,Mysql,我有下表: Comments -------- id PK cid content uid comment 好了。$cid周围的花括号并不是严格意义上的nessecary,但它们有助于避免出现这样的问题:如果您试图在之后打印文本,它会将变量名作为其他内容读取 $q="SELECT c.id, c.cid, c.content, c.uid, c.comment, COALESCE(t.title,i.title) AS the_title FROM comm

我有下表:

Comments -------- id PK cid content uid comment 好了。$cid周围的花括号并不是严格意义上的nessecary,但它们有助于避免出现这样的问题:如果您试图在之后打印文本,它会将变量名作为其他内容读取

$q="SELECT c.id, c.cid, c.content, c.uid, c.comment,
    COALESCE(t.title,i.title) AS the_title
    FROM comments c LEFT JOIN threads t ON (c.cid=t.id AND c.content='thread')
                    LEFT JOIN images i ON (c.cid=i.id AND c.content='image');

上面将两个查询组合在一起,并将title属性放在一列中

@George Stocker:你的编辑使问题更难阅读。+1代表创造性的解决方案-1,因为它是罕见的(我第一次看到COALESCE),并且会混淆一个新站点。COALESCE获取其参数列表中的第一个非NULL值并输出它。如果您的查询中有几个字段是互斥的,或者需要按特定的优先顺序选择,那么它非常有用。
 while ($row = mysql_fetch_assoc($rs)) {
   if($row['content'] == "image") {
        echo "?imgID={$cid}";
        $title = mysql_fetch_assoc(mysql_query("SELECT title from images WHERE id = '$cid'");
   } elseif ($row['content'] == "thread") {
        echo "?threadID={$cid}";
        $title = $row['title']; // Will only work as long as there is no title field in comments, oherwise use threads.title
   }
 }
 echo $title;
$q="SELECT c.id, c.cid, c.content, c.uid, c.comment,
    COALESCE(t.title,i.title) AS the_title
    FROM comments c LEFT JOIN threads t ON (c.cid=t.id AND c.content='thread')
                    LEFT JOIN images i ON (c.cid=i.id AND c.content='image');