2017-03-12 110 views
3

这是我的表的一个例子。对于给定的post_id(这是帖子的元数据),我在多行上有多个条目。需要此SQL查询帮助

post_id | meta_key | meta_value 
________ __________ ___________ 
     |   | 
1  | _theDate | 2016-03-31 
1  | _email | [email protected] 
2  | _theDate | 2016-01-06 
2  | _email | [email protected] 
3  | _theDate | 2017-02-14 
3  | _email | [email protected] 
4  | _theDate | 2016-10-01 
4  | _email | [email protected] 
5  | _theDate | 2016-09-25 
5  | _email | [email protected] 
6  | _theDate | 2015-11-19 
6  | _email | [email protected] 

我试图做到:

我想找到的电子邮件地址[email protected],并在元数据中的一年“2016”后的所有实例,再算上那些个别职位,查明用户[email protected]在2016年“有多少帖子”。

目前我已经成功使用

SELECT DISTINCT post_id 
FROM metatable 
WHERE meta_value LIKE '%[email protected]%' 

这种计算该用户的总职位,但不是写在2016年

只有那些发现的电子邮件地址的唯一实例
+1

也许通过一些相关的问题搜索;这是相当简单的东西。 – Strawberry

+0

我试过了。我一直在与这个战斗数小时! :D –

+1

SELECT post_id,count(post_id)as totalPosts FROM metatable WHERE meta_value LIKE'%[email protected]% AND meta_value LIKE%2016% –

回答

2

下面是一个使用的AGGRE两个层面的一种方法gation:

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

编辑:缺少报价

+0

非常感谢! :D –

+1

错过了一个报价。 – nogad

+0

这两个属性对于实体可能不是共同的,这没关系吗? – Strawberry

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 = '[email protected]' AND 
     EXISTS (
       SELECT 1 
       FROM table 
       WHERE post_id = t.post_id AND YEAR(meta_value) = 2016 
         meta_key = '_theDate' AND meta_value = xxx 
      ); 
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 = '[email protected]' 
0

开始用自己加入该表中,为了得到一个 'ID用户的最新' 结构表:

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 = '[email protected]' 
and date.meta_value like '2016%'; 
0

考虑到你想计算所有的meta_key是“_theDate”选择将:

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