SQL查询,SELECT不在其他表连接上的2个以上记录

时间:2016-08-22 04:14:12

标签: mysql

所以我有这两张桌子: 1. private_information

| account_no | name   | adrress   |
-----------------------------------
| 123        | andrew | alberque  |
| 234        | melissa| california|
| 456        | matthew| newark    |

然后第二个表是事务:

| account_no | transaction_num   |
----------------------------------
| 123        | 989890808         |
| 123        | 234247827         |
| 123        | 123621472         |
| 123        | 457465745         |
| 234        | 435446545         |

所以我想做出这个选择条件:

SELECT * 
From private_information a 
JOIN transaction b ON a.account_no=b.account_no 
WHERE ( <= 2 records in transation table)

帐号不应超过2个交易号记录,因此account _no = 123不应显示。

3 个答案:

答案 0 :(得分:2)

使用子查询添加联接,该子查询计算每个帐户的事务数。

SELECT p.*, t1.*
FROM private_information AS p
JOIN transaction AS t1 ON p.account_no = t1.account_no
JOIN (SELECT account_no
      FROM transaction
      GROUP BY account_no
      HAVING COUNT(*) <= 2) AS t2 ON p.account_no = t2.account_no

答案 1 :(得分:1)

我们走了

SELECT * 
FROM private_information a JOIN 
    ( SELECT count(account_no) as counted, 
      account_no 
      FROM transaction 
      HAVING counted <= 2 
      GROUP BY account_no ) b 
ON a.account_no = b.account_no

答案 2 :(得分:0)

    select AA.account_no, AA.name, AA.adrress, CC.transaction_num from 
    (
        select account_no, name, adrress from private_information 
    ) AA inner join
    ( select count(*) as cc, account_no from transation group by account_no having cc <= 2 
    ) BB ON BB.account_no = AA.account_no inner join 
    (
      select account_no, transaction_num from transaction
    ) CC ON CC.account_no = AA.account_no