在多对多关系上创建简单选择

时间:2017-11-08 07:28:21

标签: mysql postgresql rdbms

让我说我有这个表:

country:
country_id,
country_name;

currency:
currency_id,
currency_name;

country_currency:
country_id,
currency_id;

我想选择并显示所有拥有两种或更多货币的国家/地区。我的查询应该如何?

1 个答案:

答案 0 :(得分:0)

使用公共列加入所有表,然后按country_id对结果进行分组,并计算每个组的行数(或货币),如下所示。

SELECT A.COUNTRY_ID, COUNT(*) NUMBER_OF_CURRENCY 
FROM COUNTRY A 
    INNER JOIN COUNTRY_CURRENCY B ON A.COUNTRY_ID = B.COUNTRY_ID 
    INNER JOIN CURRENCY C ON B.CURRENCY_ID=C.CURRENCY_ID
GROUP BY A.COUNTRY_ID 
HAVING NUMBER_OF_CURRENCY > 1 ;

更好的查询是:

SELECT COUNTRY_NAME 
FROM COUNTRY 
WHERE COUNTRY_ID IN (
                    SELECT COUNTRY_ID 
                    FROM COUNTRY_CURRENCY 
                    GROUP BY COUNTRY_ID 
                    HAVING COUNT(*) > 1
                     );