MySQL选择具有两个条件的行,并使用相同的列ID计数大于1的行

时间:2014-01-26 12:47:39

标签: php mysql count having-clause

在此示例中,结果应为conversation_id 165337:

enter image description here

这是我到目前为止所使用的MySQL不起作用:

$value1 = $this->_getDb()->fetchCol("
SELECT conversation_id              
FROM xf_conversation_recipient
WHERE user_id = '4465'
AND user_id = '1'
HAVING COUNT(DISTINCT conversation_id) > 1
");

以下是有效的答案和代码:

$value1 = $this->_getDb()->fetchCol("
SELECT conversation_id, COUNT(*) c 
FROM xf_conversation_recipient
WHERE user_id IN ('4465','1') 
GROUP BY conversation_id HAVING c > 1
");

3 个答案:

答案 0 :(得分:1)

然后试试这个:

SELECT conversation_id, COUNT(*) c 
FROM xf_conversation_recipient  
GROUP BY conversation_id HAVING c > 1;

,在你的情况下:

$value1 = $this->_getDb()->fetchCol("
SELECT conversation_id, COUNT(*) c 
FROM xf_conversation_recipient
WHERE user_id IN ('4465','1') 
GROUP BY conversation_id HAVING c > 1
");

答案 1 :(得分:0)

WHERE user_id = '4465' AND user_id = '1' 

正确

WHERE user_id  = '4465' OR user_id = '1' 

答案 2 :(得分:0)

$value1 = $this->_getDb()->fetchCol("
SELECT conversation_id FROM xf_conversation_recipient WHERE user_id IN ('4465','1') HAVING COUNT(*) > 1
");