简体   繁体   English

如何根据外键从表中获取多个值?

[英]How to fetch multiple values from the table based on foreign key?

I have two tables,我有两张桌子,

#table 1 contains the following data structure #table 1包含以下数据结构

NO category_name    category_code   amount   type
1  provident_fund       PF           1000   Deduction
2  Home Allowance       HM           12000  Earning
3  Basic_pay            BP           35000  Earning

#table 2 contains the following data structure #table 2包含以下数据结构

NO group_name         payroll_cat_name 
1  permanent          PF,HM,BP,TX
1  visiting           HM,BP

from the table 2, I can get the value of payroll_cat_name using the query从表 2 中,我可以使用查询获取 payroll_cat_name 的值

$a = "Select payroll_cat_name from table_2";

using the above query, I'm getting the value PF,HM,BP,TX .使用上面的查询,我得到了值PF,HM,BP,TX

Now, I have to use this multiple values PF,HM,BP,TX in order to get the sum amount from table 1.现在,我必须使用多个值PF,HM,BP,TX才能从表 1 中获得总和。

Following is my code that I have tried,以下是我尝试过的代码,

include "../db.php";
$a = "Select payroll_cat_name from table_2";
$b = mysqli_query($con,$a);
$c = mysqli_fetch_array($b);
$d = $c["payroll_cat_name"];
echo "$d";
    $myArray = explode(',', $d);
    
print_r($myArray);
$tr = "select SUM(amount) as am from table_1 where category_code in ($d)";

$rt = mysqli_query($con,$tr);
$new = mysqli_fetch_array($rt);
$gh = $new["am"];

That's a poor data model.这是一个糟糕的数据 model。 There should be a separate table to store the relation between groups and categories, which each tuple on a different row.应该有一个单独的表来存储组和类别之间的关系,每个元组在不同的行上。 The linked commented by sticky bit on the question gives great explanation on how and why.由sticky bit评论的链接对问题的方式和原因给出了很好的解释。

For your current structure, one option using uses find_in_set() and a subquery:对于您当前的结构,使用find_in_set()和子查询的一个选项:

select t2.*,
    (
        select sum(t1.amount)
        from table_1 t1
        where find_in_set(t1.category_code, t2.payroll_cat_name)
    ) as t1_amount
from table_t2 t2

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

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