如何将两个选择和查询语句连接在一起

时间:2015-02-26 23:24:03

标签: mysql

我尝试使用不同的方法将来自MySQL数据库的2个选择语句查询组合成一个来自此站点之外的其他类似回答问题,但我不断收到语法错误。我曾尝试使用union和join但似乎无法找到正确的方法。我试图显示列成本和列点击总和的总和。

我也很好奇如何在表格中并排回应2个结果?我得到的结果是回显$ test1(参见下面的完整代码)并且知道如何在表中回显它但是我如何回显两个结果并将两个总和分成两个表行?

选择语句:

$query = mysql_query("SELECT SUM(clicks) AS TotalItemsClicked FROM venue_clicks Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'");

$query = mysql_query("SELECT SUM(cost) AS TotalItemsCost FROM venue_clicks Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'");

我试过这个,但是我一直遇到语法错误

$query = mysql_query("SELECT SUM(clicks) AS TotalItemsClicked FROM venue_clicks 
Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'") 

UNION (also tried JOIN here) 

$query = mysql_query("SELECT SUM(clicks) AS TotalItemsOrdered FROM venue_clicks 
Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'");

我也试过像

这样的东西
$query = mysql_query("SELECT SUM(clicks) AS TotalItemsCost AND SUM(Cost) AS TotalItemsCost 
FROM venue_clicks Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'");

这是完整的代码。我只是在运行一个查询时连接正常并获得结果。有人可以帮忙吗?

$query = mysql_query("SELECT SUM(clicks) AS TotalItemsOrdered FROM venue_clicks 
Where date > DATE_SUB(NOW(), INTERVAL 1 MONTH) AND `username` = '".$_SESSION['username']."'");




$test1 = mysql_fetch_array($query);

echo "$test1[0]";

1 个答案:

答案 0 :(得分:0)

您不需要联合或联接,因为两者都引用表/视图并具有相同的条件。

$query = "select sum(clicks) as TotalItemsClicked, sum(cost) AS TotalItemsCost
from venue_clicks
where date > date_sub(now(), interval 1 month)
and username = '".$_SESSION['username']."'");

此外,您应该使用PDOMysqli代替deprecated mysql函数来查询您的数据库。