CREATE TABLE Institutions
(
Institution_ID INTEGER PRIMARY KEY,
Institution_Name VARCHAR(200))
CREATE TABLE Contact_Persons
(
Contact_No INTEGER PRIMARY KEY,
First_Name VARCHAR(60) NOT NULL,
Last_Name VARCHAR(60) NOT NULL,
Institution_ID INTEGER,
FOREIGN KEY (Institution_ID) REFERENCES Institutions(Institution_ID))
如何编写一个mysql查询,显示拥有多个联系人的机构?查询应显示表机构中的Institution_ID和Institution_Name。以下查询有效,但仅显示Institution_ID。我也希望看到Institution_Name。我认为这两个表之间必须有一个连接。请帮忙。
SELECT Institution_ID
FROM Contact_Persons
GROUP BY Institution_ID
HAVING COUNT(*)>1;
答案 0 :(得分:0)
试试这个
SELECT I.Institution_ID,I.Institution_name
FROM Contact_Persons as C inner join Institutions as I on
C.Institution_ID=I.Institution_ID
GROUP BY I.Institution_ID,I.Institution_name
HAVING COUNT(*)>1;
答案 1 :(得分:0)
你是对的,你只需要加入你的两个表,并确保你也按照你想要选择的所有内容进行分组(除非它是一个聚合),所以在这种情况下,将Institution_Name
添加到组中子句:
SELECT i.Institution_ID, i.Institution_Name
FROM Contact_Persons AS cp
INNER JOIN Institutions AS i
ON i.Institution_ID = cp.Institution_ID
GROUP BY i.Institution_ID, i.Institution_Name
HAVING COUNT(*) > 1;