将两个SQL语句组合为一个语句

时间:2012-01-09 00:38:43

标签: sql

我已经考虑将多个sql语句合并为一个但无法使其工作。

我基本上有两个语句,我想将它们组合成一个将被查询的语句。

以下是两个陈述:

$sql="SELECT DISTINCT u.".($config->realnames ? "name" : "username")." AS displayname, u.id 
FROM (#__users AS u INNER JOIN #__uddeim AS um ON u.id=um.fromid)
WHERE um.toid=".(int)$myself." AND um.totrash=0 AND `um`.`delayed`=0".$filter.


$sql2="SELECT DISTINCT u.".($config->realnames ? "name" : "username")." AS displayname, u.id 
FROM (#__users AS u INNER JOIN #__uddeim AS um ON u.id=um.toid)
WHERE um.fromid=".(int)$myself." AND um.totrashoutbox=0".$filter." AND um.systemflag=0"

这是我尝试使用两个别名“u”和“o”组合它们:

$filter="";
if ($filter_user) $filter = " AND um.fromid=".(int)$filter_user;
if ($filter_user==-1) $filter = " AND um.fromid=0";
if ($filter_unread) $filter .= " AND um.toread=0";
if ($filter_flagged) $filter .= " AND um.flagged<>0";

$sql=  "SELECT DISTINCT u.".($config->realnames ? "name" : "username")." AS displayname, u.id,  o.".($config->realnames ? "name" : "username")." AS displayname, o.id
FROM (#__users AS u INNER JOIN #__uddeim AS um ON u.id=um.fromid) INNER JOIN #__uddeim AS om ON o.id=om.toid
WHERE um.toid=".(int)$myself." AND um.totrash=0 AND `um`.`delayed`=0".$filter. " AND om.fromid=".(int)$myself." AND om.totrashoutbox=0".$filter." AND om.systemflag=0";

但是这没有结果,前两个语句单独工作正常。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

$sql="
SELECT
    DISTINCT u.".($config->realnames ? "name" : "username")." AS displayname,
    u.id 
FROM
    (#__users AS u
INNER JOIN
    #__uddeim AS um
ON
    u.id=um.fromid)
WHERE
    um.toid=".(int)$myself."
AND
    um.totrash=0
AND
    `um`.`delayed`=0".$filter."
UNION ALL
SELECT
    DISTINCT u.".($config->realnames ? "name" : "username")." AS displayname,
    u.id
FROM
    (#__users AS u
INNER JOIN
    #__uddeim AS um
ON
    u.id=um.toid)
WHERE
    um.fromid=".(int)$myself."
AND
    um.totrashoutbox=0".$filter."
AND um.systemflag=0"