Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I target an alias column name in the where clause when a same column name exists?

So in the original table SELECT id FROM drivers there is a column teamid. However in my complicated query this teamid is not used for the output.

I am using a teamid but from another table as an alias.

SELECT
    id,
    (
        SELECT
            teamid
        FROM
            attendancelist
        WHERE
            activityid = 3
            AND driverid = driver.id
    ) as teamid
FROM
    drivers

When I try to use a WHERE-clause on teamid. It uses the teamid from driver and not the alias teamid. The only way I found to avoid this, is by renaming the alias to a column name not on the driver table, such as: customteamid.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I was wondering, just like you can explicitly get teamid from driver with driver.teamid. Is there a way you can explicitly get the alias column name?

>Solution :

You can’t reference sub-query from SELECT clause in WHERE.

To do what you described you should use JOIN instead.
Something like this:

SELECT
    id,
    attendancelist.teamid
FROM
    drivers
    left join attendancelist on (
        attendancelist.activityid = 3
        AND attendancelist.driverid = drivers.id
    )
where
    attendancelist.teamid = 100500 -- YOU CONDITION HERE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading