0

我有两张桌子。一个是:

+--------------------------+-------------+------+-----+---------+
| Field                    | Type        | Null | Key | Default |  
+--------------------------+-------------+---------+-----+------+ 
| facility_id              | int(10)     | NO   | PRI | NULL    |  
| facility_name            | varchar(30) |      |     | NULL    |                 
| facility_model           | varchar(25) |      |     | NULL    |                 
+--------------------------+-------------+------+-----+---------+ 

另一个是:

+--------------------------+-------------+------+-----+---------+
| Field                    | Type        | Null | Key | Default | 
+--------------------------+-------------+---------+-----+------+ 
| facility_id              | int(10)     | NO   | PRI | NULL    | 
| facility_serial_number   | varchar(30) |      |     | NULL    |                 
+--------------------------+-------------+------+-----+---------+

不同的设施可能有相同的设施序列号(这是我们想要找出并修复的)。我想获取其设施序列号多次出现的设施的所有信息。

我尝试使用 group by 并具有:

select f1.facility_id, f1.facility_name, f1.facility_model, f2.facility_serial_number
from f1, f2 on f1.facility_id = f2.facility_id
group by f2.facility_serial_number
having count (facility_serial_number) > 2

这是错误的。我也尝试了其他方法,但没有成功。corerct 查询语法是什么?

4

3 回答 3

0

目前尚不清楚您的 sql 的意图是什么,但正确的语法类似于

select  f1.facility_id, 
        f1.facility_name, 
        f1.facility_model, 
        f2.facility_serial_number 
from    f1 INNER JOIN
        f2  on  f1.facility_id = f2.facility_id 
group by    f1.facility_id, 
            f1.facility_name, 
            f1.facility_model, 
            f2.facility_serial_number
having count (facility_serial_number) > 2

或者

select  f2.facility_serial_number 
from    f1 INNER JOIN
        f2  on  f1.facility_id = f2.facility_id 
group by    f2.facility_serial_number
having count (facility_serial_number) > 2

但是,如果我理解正确,您可能想尝试类似

select  f1.facility_id, 
        f1.facility_name, 
        f1.facility_model, 
        f2.facility_serial_number 
from    f1 INNER JOIN
        f2  on  f1.facility_id = f2.facility_id 
WHERE   f2.facility_serial_number IN (
                                        select  f2.facility_serial_number 
                                        from    f1 INNER JOIN
                                                f2  on  f1.facility_id = f2.facility_id 
                                        group by    f2.facility_serial_number
                                        having count (facility_serial_number) > 2
                                    )
于 2012-09-17T06:01:12.057 回答
0

尝试关注参考

SELECT f1.facility_id, f1.facility_name, f1.facility_model, f2.facility_serial_number 
FROM f1 LEFT JOIN f2 on f1.facility_id = f2.facility_id 
GROUP BY f2.facility_serial_number 
HAVING count (f2.facility_serial_number) > 2
于 2012-09-17T06:01:40.350 回答
0
select * form f1 from where facility_id in(
select facility_id where f2 group by facility_id
 having count(facility_serial_number) > 2))
于 2012-09-17T06:12:06.887 回答