我有一个问题。我想加入一个桌子"公司"在"用户"表。问题是,用户既可以是公司的作者/创建者,也可以是会员。
这意味着如果一个字段users.company为空,但字段companies.authorID填充了用户ID或 第二种情况,users.company填充了公司ID,而公司.authorID为空。
如何将公司表加入users表呢?
应该像......
LEFT JOIN companies ON companies.id = users.company AND IF users.company = '0' THEN ON companies.authorID = users.id
有没有办法在join子句中实现我想要的东西?
非常感谢!
带有完整子句的当前状态(崩溃查询)
SELECT
count(users.id),
companies.city AS selectVariable
FROM users
LEFT JOIN companies ON companies.id = users.company OR (users.company = '0' AND companies.authorID = users.id)
WHERE users.email <> '' AND users.deleted = '0'
GROUP BY companies.city
ORDER BY count(users.id) DESC
LIMIT 20 OFFSET 0
此解决方案正在运行但是def。不像我希望的那样干净......
SELECT
count(users.id),
(
CASE
WHEN users.company = '0' THEN c2.city
WHEN users.company > '0' THEN c.city
ELSE NULL
END) AS selectVariable
FROM users
LEFT JOIN companies c ON c.id = users.company
LEFT JOIN companies c2 ON c2.authorID = users.id
WHERE users.email <> '' AND users.deleted = '0'
GROUP BY selectVariable
ORDER BY count(users.id) DESC
LIMIT 20 OFFSET 0
答案 0 :(得分:0)
是的,您可以在or
:
join
条件
LEFT JOIN companies c ON c.id = u.company
OR (u.company = '0' AND c.authorID = u.id)