简体   繁体   English

用条件连接 3 个表

[英]Joining 3 tables with conditions

Need to get the results from 3 tables.需要从 3 个表中获取结果。

Table1: users表1:用户

Attr.:user_id, user_code, active属性:user_id、user_code、活动

Table2: user_addresses表 2:用户地址

Attr.: user_address_id, user_id, [address fields], active属性:user_address_id、user_id、[地址字段]、活动

Table3: user_details表 3:user_details

Attr.: user_detail_id, user_id, [detail fields], active Attr.: user_detail_id, user_id, [detail fields], active

active is the boolean field. active是布尔字段。 In user_addresses and user_details , an user_id can have more than one row (say 3 rows).user_addressesuser_details ,一个 user_id 可以有不止一行(比如 3 行)。 2 rows will be having active field set to 0 (inactive). 2 行将active字段设置为 0(非活动)。 The 3rd row is the active one with active field set to 1.第 3 行是active字段, active字段设置为 1。

Now, I want to join all these tables when I search with user_code .现在,我想在使用user_code搜索时加入所有这些表。 I compiled the following join query:我编译了以下连接查询:

SELECT "*" FROM "users" 
LEFT JOIN "user_details" AS "ud" USING ("user_id") 
LEFT JOIN "user_addresses" AS "ua" USING ("using_id") 
WHERE "user_code" = 'TRY001' AND "users"."active" = 1 AND "ua"."active" = 1 AND "ud"."active" = 1

I get the result as expected only when there are entry in all tables.只有当所有表中都有条目时,我才能得到预期的结果。 So I changed to something like this:所以我改成了这样:

SELECT "*" FROM "users" 
LEFT JOIN "user_details" AS "ud" USING ("user_id") 
LEFT JOIN "user_addresses" AS "ua" USING ("using_id") 
WHERE "user_code" = 'TRY001' AND "users"."active" = 1 OR "ua"."active" = 1 OR "ud"."active" = 1

This time I get the first row (which is inactive), rather than active one.这次我得到了第一行(非活动的),而不是活动的。

What I need actually is:我真正需要的是:

  1. Join three tables连接三个表
  2. Get only the active rows from user_addresses and user_details tables仅从user_addressesuser_details表中获取活动行
  3. Incase there are no active rows / no record exist in user_addresses and user_details table, I just want to return the column name with NULL values in it.如果user_addressesuser_details表中没有活动行/没有记录,我只想返回包含 NULL 值的列名。

When you use left join , the conditions on all but the first table need to go into the ON clauses:当您使用left join ,除了第一个表之外的所有条件都需要进入ON子句:

SELECT *
FROM users u LEFT JOIN
     user_details ud
     ON ud.user_id = u.user_id AND ud.active = 1 LEFT JOIN 
     user_addresses ua 
     ON ua.using_id = ud.using_id AND ua.active = 1
WHERE u.user_code = 'TRY001' AND u.active = 1 ;

I am guessing where the columns are coming from, particularly using_id .我在猜测列的来源,特别是using_id

The reason these need to go into the ON clauses is because of what happens when there is no match.这些需要进入ON子句的原因是因为没有匹配时会发生什么。 The value is NULL and the WHERE conditions fail.该值为NULLWHERE条件失败。

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

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