简体   繁体   中英

Conditional JOIN issue, if one field is empty select other value to join with

I have an issue. I want to join a table "companies" on a "users" table. The thing is, an user can either be an author/creator of a company, or be a member.

This means in case one the field users.company is empty, but the field companies.authorID is filled with the user id or Second case, users.company is filled with the company id and companies.authorID is empty.

How can I join the companies table to the users table then?

Should be sth like

LEFT JOIN companies ON companies.id = users.company AND IF users.company = '0' THEN ON companies.authorID = users.id

Is there any way to achieve what I want within the join clause?

Thanks a lot!

Current state with complete clause (crashes the query)

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

This solution is working but def. not as clean as I would like it to be...

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

Yes, you can use or criteria in the join :

LEFT JOIN companies c ON c.id = u.company 
           OR (u.company = '0' AND c.authorID = u.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM