如何从多表mysql中选择列

时间:2014-02-07 16:20:04

标签: php mysql sql database mysqli

我有两张桌子是订阅收藏夹

subscribe [id subscribeid subscribeto datetime]
favorite [id wordid userid datetime]

所以,我想在新闻Feed中主动展示这些内容,这些新闻可以在每个循环中分开,从哪个表中来看?我的代码看起来像这样

$sql = "(SELECT * FROM favorite) UNION (SELECT * FROM subscribe) ORDER BY datetime DESC";
$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
    if($array['wordid']!=""){
        echo "This's favorite feed";
    }else{
        echo "This's subscribed feed";
    }
    //echo $array['wordid'];
    echo "<hr />";
}

if($ array ['wordid']!=“”)的条件下我觉得它应该有效,但是当在回声中注释时它始终有一个值,我不知道我知道为什么会这样。
请帮助或建议,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用别名功能来合并结果集。根据cate字段,您可以确定表格的结果。

使用mysqli扩展而不是mysql

<?php

$sql = "SELECT id, 
subscribeid As common_id, 
subscribeto, 
datetime, 'subscribe' As cate
FROM subscribe
UNION
SELECT id, 
wordid As common_id, 
userid As subscribeto, 
datetime,
 'favorite' As cate
 FROM favorite";

$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
    if($array['cate']!="subscribe"){
        echo "This's favorite feed";
    }else{
        echo "This's subscribed feed";
    }
    //echo $array['wordid'];
    echo "<hr />";
}