MYSQL在同一个表中连接操作

时间:2012-08-28 06:42:11

标签: mysql

SELECT DISTINCT mp.Group_Name FROM measurement_test mt, measurement_point mp, measurement_values mv 
                        WHERE mt.Test_ID = mv.Test_ID AND mv.Point_ID = mp.Point_ID AND mt.ID_Number = 'WR20120603_05' 


SELECT DISTINCT mp.Group_Name FROM measurement_test mt, measurement_point mp, measurement_values mv 
                        WHERE mt.Test_ID = mv.Test_ID AND mv.Point_ID = mp.Point_ID AND mt.ID_Number = 'WR20120603_04'

以上是我在网页中使用的两个查询。实际上我只想获得两个查询之间结果的公共group_name值,是否有任何其他可行的方法来实现这个特定的场景,或者只是简单地处理上述两个查询?

2 个答案:

答案 0 :(得分:2)

SELECT mp.Group_Name 
FROM measurement_test mt
inner join measurement_values mv on mt.Test_ID = mv.Test_ID
inner join measurement_point mp on mv.Point_ID = mp.Point_ID
WHERE mt.ID_Number in ('WR20120603_04', 'WR20120603_05')
group by mp.Group_Name
having count(distinct mt.ID_Number) = 2

答案 1 :(得分:1)

您可以使用IN子句简化它。

SELECT DISTINCT mp.Group_Name 
FROM    measurement_test mt
            INNER JOIN measurement_point mp
                ON mt.Test_ID = mp.Test_ID
            INNER JOIN measurement_values mv 
                ON mv.Point_ID = mp.Point_ID
WHERE   mt.ID_Number IN ('WR20120603_05', 'WR20120603_04')
GROUP BY    mp.Group_Name 
HAVING      COUNT(mp.Group_Name) = 2