SQL - Where子句和distinct

时间:2015-09-30 21:05:09

标签: php mysql sql pdo

我正在尝试使用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.tokenb.token匹配的记录的 金额 clickcount

我怎样才能做到这一点?

2 个答案:

答案 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.tokenb.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;