需要有关此SQL查询的帮助

时间:2017-03-12 20:26:34

标签: php mysql sql phpmyadmin

这是我的表的一个例子。对于给定的post_id,我在多行上有多个条目(这是帖子的元数据)。

post_id | meta_key | meta_value
________ __________ ___________
        |          |
1       | _theDate | 2016-03-31 
1       | _email   | the@email.com
2       | _theDate | 2016-01-06 
2       | _email   | the@email.com
3       | _theDate | 2017-02-14 
3       | _email   | other@user.net
4       | _theDate | 2016-10-01 
4       | _email   | the@email.com
5       | _theDate | 2016-09-25 
5       | _email   | other@user.net
6       | _theDate | 2015-11-19 
6       | _email   | other@user.net

我想要完成的任务:

我想查找邮件地址the@email.com和年份" 2016年"在元数据中,然后计算这些单独的帖子,以查找用户the@email.com在一年中所写的帖子数量" 2016"。

目前我设法只使用

查找电子邮件地址的实例
SELECT DISTINCT post_id 
FROM  metatable 
WHERE meta_value LIKE '%the@email.com%'

这会计算该用户的总帖子数,但 仅计入2016年的帖子。

5 个答案:

答案 0 :(得分:2)

以下是一种使用两级聚合的方法:

SELECT COUNT(*)
FROM (SELECT post_id
      FROM  metatable 
      WHERE (meta_key = '_email' AND meta_value = 'the@email.com') OR
            (meta_key = '_theDate' AND LEFT(meta_value, 4) = '2016')
      GROUP BY post_id
      HAVING COUNT(DISTINCT meta_key) = 2
     ) p;

编辑:缺少报价

答案 1 :(得分:0)

你走了:

SELECT t.post_id -- Replace with `SELECT count(*)` to just have the total
FROM table t
WHERE t.meta_key = '_email' AND t.meta_value = 'the@email.com' AND 
      EXISTS (
                SELECT 1
                FROM table
                WHERE post_id = t.post_id AND YEAR(meta_value) = 2016
                      meta_key = '_theDate' AND meta_value = xxx
             );

答案 2 :(得分:0)

SELECT
    COUNT(*)
FROM
    metatable m1
    INNER JOIN metatable m2 ON m2.post_id = m1.post_id
WHERE
    AND m1.meta_key = _theDate
    AND m1.meta_value LIKE '2016%'
    AND m2.meta_key = _email
    AND m2.meta_value = 'the@email.com'

答案 3 :(得分:0)

首先加入自己的表格,以便获得一个“用户 - 日期”'结构化表格:

SELECT email.post_id, email.meta_value as mail, date.meta_value as date from metatable as email
 inner join metatable as dateTable
 on email.post_id = dateTable.post_id
 and email.meta_key = '_email'
 and dateTable.meta_key = '_theDate'

在那你可以做你想做的事:

SELECT count(*) from metatable as email
 inner join metatable as dateTable
 on email.post_id = dateTable.post_id
 and email.meta_key = '_email'
 and dateTable.meta_key = '_theDate'
 where
 email.meta_value = 'the@email.com'
 and date.meta_value like '2016%';

答案 4 :(得分:0)

考虑到你想要计算meta_key的所有位置" _theDate"选择将:

SELECT COUNT(1) FROM table WHERE YEAR(aux_meta_value) = "2016" AND meta_key = '_theDate'