[英]SQL comparison condition column to choose the table to JOIN
GENERAL table: 一般表:
| id | name | type_id |
SECONDARY1 table: SECONDARY1表:
| id | general_id | erynda_kakayato | byaka |
SECONDARY2 table: SECONDARY2表:
| id | general_id | konkretnaya_hren |
How to combine GENERAL table and one of the SECONDARY using the value of the column to GENERAL.TYPE_ID? 如何使用GENERAL.TYPE_ID的列值将GENERAL表和SECONDARY之一合并? The following query does not work, but the logic should be like this.
以下查询不起作用,但是逻辑应该是这样的。
SELECT *
FROM GENERAL
JOIN (CASE WHEN types_id = 1 THEN 'SECONDARY1'
WHEN types_id = 2 THEN 'SECONDARY2' END) AS t
ON GENERAL.id = t.id
This request is necessary because values of type changing table for the join. 此请求是必需的,因为联接的类型更改表的值。 Use of the same table impossible because the property and the number of columns in different tables depending on the column type GENERAL.
不能使用同一表,因为不同表中的属性和列数取决于列类型GENERAL。
Try this: 尝试这个:
SELECT g.*
FROM GENERAL AS g
LEFT JOIN SECONDARY1 AS s1
ON CASE WHEN g.type_id = 1 THEN g.id END = s1.general_id
LEFT JOIN SECONDARY2 AS s2
ON CASE WHEN g.type_id = 2 THEN g.id END = s2.general_id
If type_id = 1
then only the first LEFT JOIN
operation is essentially performed, because the ON
clause of the second LEFT JOIN
becomes NULL = s2.general_id
, which can never evaluate to true
. 如果
type_id = 1
则仅本质上仅执行第一个LEFT JOIN
操作,因为第二个LEFT JOIN
的ON
子句变为NULL = s2.general_id
,该值永远无法评估为true
。
You need to select the value in the select
. 您需要选择在价值
select
。 If using left join
, you can choose the first non- NULL
value: 如果使用
left join
,则可以选择第一个非NULL
值:
select g.*, coalesce(s1.erynda_kakayato, konkretnaya_hren)
from general g left join
secondary1 s1
on s1.general_id = g.id and g.type_id = 1 left join
secondary s2
on s2.general_id = g.id and g.type_id = 2 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.