简体   繁体   English

在条件下查询LEFT JOIN

[英]Query LEFT JOIN on condition

Let's say I have a table of clients and a table of "more_information". 假设我有一个客户表和一个“more_information”表。

I query the list of clients and their additional information (not every client has entries here, so we use LEFT JOIN): 我查询客户端列表及其附加信息(并非每个客户端都有条目,所以我们使用LEFT JOIN):

 SELECT id, name, more_information.data
    FROM clients
    LEFT JOIN more_information
    ON more_information.client_id = clients.id

Now my problem: I want to query "more_information" only for clients that fulfill a condition, fe signed up in last 30 days, for the others I want just null for more_information.data 现在我的问题是:我想查询“more_information”仅适用于满足条件的客户,fe在过去30天内注册,对于其他我想要的其他人只需为null_information.data

so something like (syntax not correct) 所以像(语法不正确)

 SELECT id, name, more_information.data
    FROM clients
    CASE WHEN clients.registered > '2015-12-27 00:00:00' THEN
        LEFT JOIN more_information
        ON more_information.client_id = clients.id
    ELSE
        null
    END

I know I could use the CASE in the SELECT part, but that won't improve the performance what is my goal. 我知道我可以在SELECT部分​​使用CASE,但这不会提高性能,这是我的目标。

The reason is that the more_information JOIN queries a lot of data and has many additional conditions that make the query too slow. 原因是more_information JOIN查询了大量数据,并且有许多其他条件使得查询太慢。 I don't want to query it where it is not necessary. 我不想在没有必要的地方查询它。 Is that even possible with MySQL or do I need to split the query and make two separate queries? 甚至可以使用MySQL,还是我需要拆分查询并进行两次单独的查询?

Thanks a lot for your ideas 非常感谢你的想法

Just add to your JOIN condition 只需添加到您的JOIN条件

SELECT id, name, more_information.data
FROM clients
LEFT JOIN more_information
ON more_information.client_id = clients.id AND clients.registered > '2015-12-27 00:00:00'

An INDEX on registered , id and client_id would help performance. registeredidclient_id上的INDEX将有助于提高性能。

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

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