从第二个表中count = 1的一个表中选择另外两个条件

时间:2012-05-13 21:29:20

标签: mysql

我需要选择现金支付和相同日期的交易,但仅限于这些交易 只有一次付款(因此结果集中应省略num 14) 所以正确的结果只有12和13。

    Table2                          Table1
num  | date | data | total       num | payment | date
12      xy     abc    2.5        12      cash     xy
13      xy     cbc    2.1        13      cash     xy
14      xy     acc    2.3        14      visa     xy
19      xy     def    2.0        14      cash     xy
27      xy     fgh    1.3        19      visa     xy
                                 27       mc      xy  

这样的结果在结果集中给出了数字14,但是应该省略14。

SELECT num, data 
FROM Table2
WHERE num IN
(
SELECT num  FROM `Table1`
WHERE payment = 'cash'
GROUP BY `num`
HAVING ( COUNT(`num`) = 1  )
)        

以sumarize正确答案(通过tombom):

 SELECT t2.num, t2.data 
 FROM Table1 as t1
 INNER JOIN Table2 as t2 ON t1.num = t2.num
 AND t1.date = 'xy'  
 GROUP BY t1.num
 HAVING GROUP_CONCAT(t1.payment) = 'cash'

谢谢!

1 个答案:

答案 0 :(得分:1)

对不起,我完全误解了你的问题。以下是它的工作原理:

SELECT 
*
FROM
Table1 t1
INNER JOIN Table2 t2 ON t1.num = t2.num AND t1.date = t2.date 
GROUP BY t1.num
HAVING  GROUP_CONCAT(t1.payment) = 'cash'