这是我的问题:我有一个与不同国际项目相关的用户列表, 我想让那些专门为美国项目工作的用户,所以让我们说如果有人为德国项目工作,我不希望他在列表中。 它涉及三个表:用户,项目,公司
以下是第一个获取用于美国项目的用户的查询:
SELECT DISTINCT users.forename, users.surname, users.email, users.company_id, users.user_id
FROM projects, company, users
WHERE projects.project_type = 'US'
AND company.project_id = projects.project_id
AND users.company_id = company.company_id
ORDER BY surname, forename
现在我如何排除还有其他国家/地区项目的用户?
答案 0 :(得分:2)
您可以使用NOT IN子句排除在其他项目上工作的用户。
在条件下添加行
WHERE projects.user_id
NOT IN (select user_id from projects where projects.project_type != 'US')
答案 1 :(得分:1)
您可以加入表格并使用条件过滤
SELECT DISTINCT users.forename, users.surname, users.email, users.company_id, users.user_id
FROM users
JOIN company USING (company_id)
JOIN projects USING (project_id)
WHERE projects.project_type = 'US'
ORDER BY surname, forename
此查询创建包含用户的行以及有关公司和项目的信息,并在使用条件WHERE projects.project_type = 'US'
答案 2 :(得分:1)
您可以尝试使用HAVING。如果用户仅在美国工作,则COUNT必须为1:
SELECT DISTINCT users.forename, COUNT(projects.*) AS c, users.surname, users.email, users.company_id, users.user_id
FROM projects, company, users
WHERE projects.project_type = 'US'
AND company.project_id = projects.project_id
AND users.company_id = company.company_id
GROUP BY projects.project_type
HAVING c = 1
ORDER BY surname, forename
也许这段代码不起作用,无法检查,但你可以尝试这个方向。
答案 3 :(得分:0)
not exists
可以胜任
SELECT DISTINCT users.forename, users.surname, users.email, users.company_id, users.user_id
FROM projects, company, users
WHERE projects.project_type = 'US'
AND company.project_id = projects.project_id
AND users.company_id = company.company_id
AND NOT EXISTS (
SELECT *
FROM projects notUS
WHERE notUS.project_type <> 'US'
AND notUS.user_id = users.user_id)
ORDER BY surname, forename
答案 4 :(得分:0)
您可以使用: -
SELECT DISTINCT users.forename, users.surname, users.email, users.company_id, users.user_id
FROM projects, company, users
WHERE users.company_id = company.company_id
AND company.project_id = projects.project_id
AND projects.user_id
IN (select user_id from projects where projects.project_type = 'US')
ORDER BY surname, forename
答案 5 :(得分:0)
尝试这个我觉得你需要MINUS:
SELECT
users.forename, users.surname, users.email, users.company_id, users.user_id
FROM
users
where
user_id not in(SELECT DISTINCT user_id from users where company_id in
(
Select company_id from company where project_id = (
Select project_id from projects where project_type != 'US'
)
)
答案 6 :(得分:0)
你也可以这样做
SELECT DISTINCT
users.forename,
users.surname,
users.email,
users.company_id,
users.user_id
FROM projects
INNER JOIN company
ON company.project_id = projects.project_id
INNER JOIN users
ON users.company_id = company.company_id
INNER JOIN (SELECT *
FROM projects
WHERE project_type <> 'US') AS project
ON project.project_id = projects.project_id
WHERE project.project_id IN NULL
GROUP BY projects.project_id
ORDER BY surname, forename