Chud37
Chud37

Reputation: 5007

SQL Conditional Join?

I have a table called LOGS with the following columns:

id - user - object - ref - field - from - to - join - ts

to store logging of a PHP app I am writing. However, is it possible in the SQL query when I return all the data into PHP to do a 'conditional' join? For instance the join column might contain 'people' indicating that the field column needs to be joined in relationship with the table people.

Is this possible? Or shall I have to do it on the PHP side?

Upvotes: 3

Views: 5956

Answers (1)

Chris Moutray
Chris Moutray

Reputation: 18369

A LEFT join should do the trick here

select * 
from
    LOGS l
left join 
    PEOPLE p on p.peopleid = l.field and l.join = 'people'

I'm not sure I've used the correct relationship fields between LOGS and PEOPLE but by including a clause of join where log type is people then you can see PEOPLE entries are conditionally returned.

Things become more complicated when you want to conditionally return from different tables, because you need to make sure the extra fields, brought in by the entity table are the same (or at least are identified as the same). In which case your forced to UNION results.

select 
    l.*,
    p.peopleid as entityid, 
    p.fullname as displayname
from
    LOGS l
left join 
    PEOPLE p on p.peopleid = l.field and l.join = 'people'

union all

select 
    l.*,
    a.accountid as entityid, 
    p.accountname as displayname
from
    LOGS l
left join 
    ACCOUNT a on a.accountid = l.field and l.join = 'account'

or perhaps this

select 
    l.*,
    entity.entityid as entityid, 
    entity.displayname as displayname
from
    LOGS l
left join 
(
    select 'people' as type, p.peopleid as entityid, p.fullname as displayname
    from PEOPLE

    union all

    select 'account', a.accountid, p.accountname
    from ACCOUNT
) entity on entity.type = l.join and entity.entityid = l.field

But I can imagine combining lots of your entity tables like this to return logs could make for a really slow query.

Upvotes: 4

Related Questions