简体   繁体   English

MySQL的子查询或左联接选择丢失的列?

[英]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. 我需要对3个表执行SELECT查询,但我不知道使用子查询是否比LEFT JOIN更好,因为在某些情况下可能缺少一列。 These are the tables: 这些是表格:

Options (name, info...) 选项(名称,信息...)

Owners (name, address) 所有者(姓名,地址)

Rel (idoption, idowner) 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. SELECT应该在每个记录中返回所有带有所有者名称的选项,但是在某些情况下,该选项可能未连接到任何所有者,并且所有者名称应该为空。 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." LEFT JOIN然后,它将获得所有选项,无论是否有匹配的所有者-“对左表的这种额外考虑可以认为是一种特殊的保存方式。左表中的每个项目都将显示在MySQL中结果,即使与要连接的另一个表不匹配也是如此。”

from: http://www.tizag.com/mysqlTutorial/mysqlleftjoin.php 来自: 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). LEFT JOIN可能是适当的响应,并且可能比子查询更快,具体取决于您的结果(它们可能会编译为相同的计划)。

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. 如果在没有匹配项的情况下可以使用NULL,那是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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