Mysql:获取多个外键达到条件的数据

时间:2015-04-24 08:28:50

标签: mysql

我有两张桌子:

r_rec必要的内容是主id

r_fibu其中i_recrec的外键,sh填充hs

我想查询以查找来自id的{​​{1}} rec,其中r_fibu有多个数据集sh = h但我无法弄清楚需要查询。

这就是我现在所拥有的:

SELECT r.id
FROM `r_rec` AS r
INNER JOIN r_fibu AS f ON r.id = f.i_rec
WHERE f.sh = 'h'
HAVING COUNT( * ) >=2

1 个答案:

答案 0 :(得分:1)

要获得每count r.id,您需要group by

SELECT r.id,count(*) as tot
FROM `r_rec` AS r
INNER JOIN r_fibu AS f ON r.id = f.i_rec
WHERE f.sh = 'h'
group by r.id
having tot >=2