我正在尝试使用PDO执行SQL查询,它将从两个不同的表中选择数据,并将它们匹配在一起:
$stmt = $dbh->prepare("
select a.token, b.token, b.username, COUNT(DISTINCT a.token) adcount, COUNT(DISTINCT b.username WHERE a.token=b.token) clickcount
from advertisements a, advertisement_clicks b
where a.status='2' AND (a.clicks_left > 0 OR a.fixed ='1')
AND b.token=a.token
");
$stmt->bindParam(':userid', $userdata["id"]);
$stmt->execute();
$s1=$stmt->fetch();
所以,上面的SQL并不起作用。我正在尝试选择a.token
与b.token
匹配的记录的 金额 为clickcount
我怎样才能做到这一点?
答案 0 :(得分:1)
select
a.token, b.token, b.username, COUNT(DISTINCT a.token) adcount,
COUNT(DISTINCT b.username) clickcount
from advertisements a
JOIN advertisement_clicks b ON b.token=a.token
where a.status='2' AND (a.clicks_left > 0 OR a.fixed ='1')
您已经join
了表格。您无需在where
中使用count
子句。
答案 1 :(得分:0)
以下是选择a.token
与b.token
匹配clickcount
的记录数量的查询:
SELECT a.token, b.token, COUNT(a.token) clickcount
FROM advertisements a
JOIN advertisement_clicks b
ON b.token=a.token
WHERE a.status='2' AND (a.clicks_left > 0 OR a.fixed ='1')
GROUP BY a.token;