MySQL返回1行,包含2个语句

时间:2014-01-12 07:54:51

标签: php mysql

我希望将这2个查询作为一个,这样当我运行它时1获得1行所有数据称为ontvanger。 下面的代码不会工作,但我尝试了很多不同的代码 所以我想知道我是否可以得到一些帮助。

$getBuddies = dbquery("select sender AS ontvanger FROM messenger_friendships WHERE receiver = '30'");
$getBuddies2 = dbquery("select receiver AS ontvanger FROM messenger_friendships WHERE sender = '30'");

        $i = 0;

        while ($buddy = mysql_fetch_assoc($getBuddies, $getBuddies2));

感谢 ErichBSchulz

case 'recipients':

    echo '/*-secure-' . LB;
    echo '[';


    $getBuddies = dbquery("select sender AS ontvanger FROM messenger_friendships WHERE receiver = '" . USER_ID . "'
                            UNION select receiver AS ontvanger FROM messenger_friendships WHERE sender = '" . USER_ID . "'");   $i = 0;

    while ($buddy = mysql_fetch_assoc($getBuddies))
    {
        if ($i > 0)
        {
            echo ',';
        }

        echo '{"id":' . $buddy['ontvanger'] . ',"name":"' . clean($users->id2name($buddy['ontvanger'])) . '"}';

        $i++;
    }

3 个答案:

答案 0 :(得分:3)

SELECT sender,receiver FROM messenger_friendships WHERE receiver = '30' OR sender = '30'

只要没有多行“30”,这将返回包含所有匹配数据的1行。如果是这样,您可以使用GROUP_CONCAT()并将所有结果作为字符串返回到1行,如果您现在只需要查询返回1行。

答案 1 :(得分:0)

你想要的东西:

$getBuddies = dbquery(
"select sender AS ontvanger FROM messenger_friendships WHERE receiver = '30'
 UNION select receiver AS ontvanger FROM messenger_friendships WHERE sender = '30'");

编辑当然你也可以这样做:

$getBuddies = dbquery(
"select if(sender = '30', receiver, sender) AS ontvanger 
FROM messenger_friendships 
WHERE receiver = '30' OR sender = '30'");

但是,正如Barmar所指出的那样,这两个查询都将返回多行 - 但是在我猜测的行之间读取就是你实际所追求的。

然后关于第一个查询的好处是它将删除重复项。

答案 2 :(得分:0)

Mysql不允许多个查询。另一方面,Mysqli提供启用multiple queries的可能性。