简体   繁体   中英

MySQL Sub-Query or LEFT JOIN for SELECTing missing columns?

I need to perform a SELECT query on 3 tables and i don't know if using a sub-query could be better than a LEFT JOIN since one column in some case might be missing. These are the tables:

Options (name, info...)

Owners (name, address)

Rel (idoption, idowner)

The SELECT should return all the Options with the name of the Owner inside each record but, in some case, the Option might not be connected to any Owner and the name of the Owner should be empty. Any suggestions? Thanks in advance

LEFT JOIN then, it will get all the Options irregardless if there is a matching Owner or not - "This extra consideration to the left table can be thought of as special kind of preservation. Each item in the left table will show up in a MySQL result, even if there isn't a match with the other table that it is being joined to."

from: http://www.tizag.com/mysqlTutorial/mysqlleftjoin.php

A LEFT JOIN is likely the appropriate response and will probably be faster than a subquery depending on your results (it's possible that they'd compile to the same plan).

SELECT
    op.name
    ,op.info
    ,...
    ,ow.name
    ,ow.address
FROM
    options op
LEFT OUTER JOIN
    Rel r
        ON r.idoption = op.id
LEFT OUTER JOIN
    owners ow
        ON ow.id = r.idowner

A left join will be much more efficient and faster than a subquery. If you can live with NULLs for the cases where there's no match, it's the better approach.

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