根据table2上的条目从table1中选择结果

时间:2016-03-30 10:54:24

标签: php sql date

我有两张桌子;

banner_views (id, b_id, b_date) - 每次显示时都会记录横幅视图

banners_dynamic (id, status, static_iname, static_keywords, static_url, static_alt, static_type, static_image, b_views, b_clicks) - 存储横幅数据

我想选择3个banners_dynamic个结果,这些结果在过去7天内观看次数最少。

我确实把一些东西放在一起(见下文),但我意识到它抓住了所有横幅的总观看次数而不是唯一的id。

SELECT  *, 
(SELECT COUNT(*) FROM banner_views v WHERE v.b_date >= DATE(NOW()) - INTERVAL 7 DAY) as post_count 
FROM banners_dynamic b  
WHERE static_keywords LIKE '%test%' AND b.status='1' AND b.static_type='1' 
ORDER BY post_count ASC LIMIT 3

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

您必须将banners_dynamic表和子查询与相应的横幅ID一起加入:

SELECT
    b.*, p.b_count
FROM
    banners_dynamic b
    INNER JOIN (
        SELECT
            b_id,
            COUNT(*) AS b_count
        FROM
            banner_views v
        WHERE
            v.b_date >= DATE(NOW() - INTERVAL 7 DAY)
        GROUP BY
            b_id
    ) p on p.b_id = b.id
WHERE
    b.static_keywords LIKE '%test%'
    AND b.`status` = '1'
    AND b.static_type = '1'
ORDER BY
    p.b_count ASC
LIMIT 3

更新:即使没有子查询,您也可以这样做:

SELECT
    b.*, COUNT(v.b_id) AS b_count
FROM
    banners_dynamic b
    INNER JOIN banner_views v ON v.b_id = b.id
WHERE
    v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
    AND b.static_keywords LIKE '%test%'
    AND b.`status` = '1'
    AND b.static_type = '1'
GROUP BY
    v.b_id
ORDER BY
    b_count ASC
LIMIT 3;

如果您想要包含没有任何观看次数的横幅(次数= 0),那么您必须执行LEFT JOIN

SELECT
    b.*, COUNT(v.b_id) AS b_count
FROM
    banners_dynamic b
    LEFT JOIN banner_views v ON v.b_id = b.id
              AND v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
WHERE
    b.static_keywords LIKE '%test%'
    AND b.`status` = '1'
    AND b.static_type = '1'
GROUP BY
    v.b_id
ORDER BY
    b_count ASC
LIMIT 3;