1

我在将以下查询连接在一起以使其工作效率更高时遇到问题。有人可以告诉我如何连接这两个查询以使其只有一个吗?

$rs_duplicate = mysql_query("select count(*) as total 
                             from advertisers_account
                             where user_email='$user_email' ") or die(mysql_error());

list($total) = mysql_fetch_row($rs_duplicate);

    }

$rs_duplicate_pub = mysql_query("select count(*) as total 
                                 from publishers_account
                                 where user_email='$user_email' ") or die(mysql_error());

list($totalpub) = mysql_fetch_row($rs_duplicate_pub);


if ($totalpub ||  $total  > 0)
{
    echo "Not Available  ";

} else {

    echo "Available";
}
4

4 回答 4

1
SELECT count(advertisers_account.id)
FROM publishers_account
LEFT JOIN advertisers_account ON publisher_account.email = advertisers_account.email
WHERE publisher_account.email = '$user_email';

如果计数大于零,则电子邮件在两个表中至少存在一次。如果它仅存在于左表(发布者)中,则计数器为零。如果左表中根本不存在,那么即使右表中确实存在(广告商),您也不会得到任何行

于 2013-08-26T19:47:36.180 回答
1

使用联合:

SELECT 'advertisers' AS which, count(*) AS total
FROM advertisers_account
WHERE user_email = '$user_email'
UNION
SELECT 'publishers' AS which, count(*) AS total
FROM publishers_account
WHERE user_email = '$user_email'

此查询将返回两行,您可以使用该which列来判断它是广告商还是发布商。

于 2013-08-26T19:27:41.300 回答
1

这就是你可以做到的方式。您需要使用连接,但您应该确保不要让查询中的任何变量直接来自外部用户,例如来自表单提交。这将为您打开 SQL 注入的大门。改为使用准备好的语句。

select count(*) as total from publishers_account INNER JOIN advertisers_account ON advertisers_account.user_email = publishers_account.user_email WHERE user_email='$user_email' 
于 2013-08-26T19:28:18.273 回答
1

回应:有人可以告诉我如何连接这两个查询,以便它只有一个吗?

为什么不:

Select 
(select count(*) as total from advertisers_account where user_email='$user_email') +
(select count(*) as total from publishers_account where user_email='$user_email') as sumofCount
于 2013-08-26T19:31:41.593 回答