我仍然是mysql的新手,到目前为止只需要在我的代码中使用基本查询。但我现在需要以下内容。我有一个包含行的数据库:id,firstname,lastname,email,companyid。
我想选择所有值,其中companyid在整个数据库中只有一个。 (一些联系人共享一家公司)。其次,我需要为公司在数据库中有超过1个条目的公司选择所有首次创建的联系人。尝试了一群群体,不同,但不能让这个工作。
SELECT * FROM `contacts` WHERE (SELECT COUNT(companyid) FROM `contacts`) <2
试过这个,但显然不正确(显然)。
问候
答案 0 :(得分:1)
第一项任务:
SELECT c.*
FROM contacts c
JOIN (SELECT companyid, COUNT(*) c
FROM contacts
GROUP BY companyid
HAVING c = 1) c1
ON c.companyid = c1.companyid
第二项任务:
SELECT c.*
FROM CONTACTS c
JOIN (SELECT companyid, MIN(created) mindate, COUNT(*) c
FROM contacts
GROUP BY companyid
HAVING c > 1) c1
ON c.companyid = c1.companyid AND c.created = c1.mindate
根据第一个查询执行UPDATE:
UPDATE contacts c
JOIN (SELECT companyid, MIN(created) mindate, COUNT(*) c
FROM contacts
GROUP BY companyid
HAVING c > 1) c1
ON c.companyid = c1.companyid AND c.created = c1.mindate
WHERE yourcode = 1
SET somecolumn = newvalue
答案 1 :(得分:0)
您可能想要使用HAVING子句:
SELECT companyid,COUNT(id) as cnt FROM `contacts` group by companyid having COUNT(ID)=1
答案 2 :(得分:0)
我不确定这是否可以解决您的问题,但您可以试试这个
SELECT *, COUNT(companyid)
FROM CONTACTS
GROUP BY 1
HAVING COUNT(companyid) = 1
答案 3 :(得分:0)
SELECT c.id, c.firstname, c.lastname, c.email, c.companyid
FROM contacts c
INNER JOIN (
SELECT MIN(id) as id FROM contacts GROUP BY companyid
) c2 ON c2.id = c.id
MIN(id)将选择有多个联系人的公司中的第一个创建(最早)。 GROUP BY将确保每个companyid一行