从2个表中选择如果T1 =在T2上为id

时间:2013-11-27 13:53:39

标签: mysql select where

我想做类似的事情:

$dnt = mysql_query('select * from topics WHERE parent != "5" order by timestamp DESC limit 5 ');
while($dnnt = mysql_fetch_array($dnt)){

$dlk = mysql_query('select * from users where id="'.$dnnt['authorid'].'"');

}

我认为我需要使用类似的东西:

$dn1 = mysql_query('select c.XX, c.XXXXX, c.XXX, c.XXX,
(select count(t.XX) from YY as t where t.XXX=c.XX and t.XX1=1) as YY,
(select count(t2.XX) from YY as t2 where t2.XXX=c.XX and t2.XX2!=1) as YYY from YYY as c where c.XXXXX = "...." or c.XXXXX= "..."  group by c.XX order by c.XXX
asc ');

1 个答案:

答案 0 :(得分:0)

您应该使用JOIN声明:

SELECT `topics`.*,
       `users`.*
  FROM `topics`
INNER JOIN `users` ON `topics`.`authorid` = `users`.`id`
WHERE `topics`.`parent` != 5
ORDER BY `topics`.`timestamp` DESC 
LIMIT 5 

还应该告知您,mysql_*系列函数现已弃用。您应该考虑使用MySQLiPDO

此外,当您使用SELECT *时,您很少需要所有内容