检查记录是否来自table_b

时间:2013-01-01 01:21:44

标签: php mysql

我有两个表(table_a和table_b)和一个UNION。

如何检查记录是否为table_a。

我试过了,但没有工作:

$res=mysql_query("(SELECT id, added FROM table_a WHERE user_id = '".$uid."') 
UNION 
(SELECT id as comments, added FROM table_b WHERE user_id = '".$uid."') ORDER BY added DESC LIMIT 50");

if(!empty($rows["comments"])) // not working

1 个答案:

答案 0 :(得分:3)

它无法正常工作,因为您忘记阅读结果集:

while ($row = mysql_fetch_assoc($res)) {
// here you read $rows["comments"] etc
...

}

重要:
请不要使用mysql_*函数,它已被弃用(请参阅red box)并且容易受到sql-injection的攻击。
使用PDOMySQLi

<强>更新
如果您想知道结果“来自”哪个表,您可以将查询更改为:

(SELECT id, added, 'A' as came_from FROM table_a WHERE user_id = '".$uid."') 
UNION 
(SELECT id as comments, added, 'B' as came_from FROM table_b WHERE user_id = '".$uid."') ORDER BY added DESC LIMIT 50

然后检查:$rows["came_from "]

的值