简体   繁体   English

使用Laravel或PHP在mysql表上建立条件关系

[英]Make conditional relation on mysql tables using Laravel or PHP

I have tables like below. 我有如下表格。

Table A 表A.

id  | val_a
1   | a1
2   | a2
3   | a3

Table B 表B.

id  | id_a| val_b | resource_type
1   | 2   | b1    |  1
2   | 2   | b2    |  2
3   | 3   | b3    |  3
4   | 3   | b4    |  3

Table Resource_A 表资源_A

id  |r_val| id_b
1   | ra1 | 1

Table Resource_B 表Resource_B

id  |r_val| id_b
1   | rb1 | 2

Table Resource_C 表Resource_C

id  |r_val| id_b
1   | rc1 | 3
2   | rc2 | 4

If resource_type is 1 in Table B , then table B make relation with table Resource_A . 如果表B resource_type为1,则表B与表Resource_A建立关系。

If resource_type is 2 in Table B , then table B make relation with table Resource_B . 如果表B resource_type为2,则表B与表Resource_B建立关系。

If resource_type is 3 in Table B , then table B make relation with table Resource_C . 如果表B resource_type为3,则表B与表Resource_C建立关系。

Required Output is: 要求的输出是:

id_b | id_a| val_b |val_a | resource_type| r_val
 1   | 2   | b1    |  a1  |    1         | ra1 
 2   | 2   | b2    |  a2  |    2         | rb1 
 3   | 3   | b3    |  a3  |    3         | rc1 
 4   | 3   | b4    |  a3  |    3         | rc2

But what is the best way to get it without using loop in laravel? 但是,如果不在laravel中使用循环,那么获得它的最佳方法是什么?

How Can I achieve this by using Laravel 5.2 OR Laravel 4 OR PHP OR MYSQL Query? 如何使用Laravel 5.2或Laravel 4或PHP或MYSQL查询实现此目的?

Thanks Ahead. 谢谢你。

You only need to join the tables together as I have done below. 您只需要像下面一样将表连接在一起。 The tricky part here is bringing in the correct r_val from the three resource tables. 这里棘手的部分是从三个资源表中引入正确的r_val We can do this by left joining to each resource table, and then using the following expression to grab the matching value: 我们可以通过左连接到每个资源表,然后使用以下表达式来获取匹配值:

COALESCE(t1.r_val, t2.r_val, t3.r_val) AS r_val

This will take the first non NULL value from a resource table, in order of left to right. 这将从资源表中按照从左到右的顺序获取第一个非NULL值。 Assuming that each ID from tableb only appears once, in one of the resource tables, the order of the terms inside COALESCE() should not matter. 假设tableb中的每个ID只出现一次,在其中一个资源表中, COALESCE()内的术语顺序无关紧要。

SELECT tb.id AS id_b,
       tb.id_a,
       tb.val_b,
       COALESCE(ta.val_a, 'NA') AS val_a,
       tb.resource_type,
       COALESCE(t1.r_val, t2.r_val, t3.r_val) AS r_val
FROM tableb tb
LEFT JOIN tablea ta
    ON tb.id_a = ta.id
LEFT JOIN resource_a t1
    ON tb.id = t1.id_b
LEFT JOIN resource_b t2
    ON tb.id = t2.id_b
LEFT JOIN resource_c t3
    ON tb.id = t3.id_b

Demo here: 在这里演示:

SQLFiddle SQLFiddle

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

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