如何根据外键从 table 中获取多个值?
How to fetch multiple values from the table based on foreign key?
我有两个table,
#table1包含以下数据结构
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
#table2包含以下数据结构
NO group_name payroll_cat_name
1 permanent PF,HM,BP,TX
1 visiting HM,BP
从 table 2,我可以使用查询
获取 payroll_cat_name 的值
$a = "Select payroll_cat_name from table_2";
使用上面的查询,我得到值 PF,HM,BP,TX
。
现在,我必须使用这个多个值 PF,HM,BP,TX
才能从 table 1.
中获得总金额
以下是我试过的代码,
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"];
这是一个糟糕的数据模型。应该有一个单独的 table 来存储组和类别之间的关系,每个元组在不同的行上。 sticky bit 对问题的链接评论给出了关于如何以及为什么的很好的解释。
对于您当前的结构,一个选项使用 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
我有两个table,
#table1包含以下数据结构
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
#table2包含以下数据结构
NO group_name payroll_cat_name
1 permanent PF,HM,BP,TX
1 visiting HM,BP
从 table 2,我可以使用查询
获取 payroll_cat_name 的值$a = "Select payroll_cat_name from table_2";
使用上面的查询,我得到值 PF,HM,BP,TX
。
现在,我必须使用这个多个值 PF,HM,BP,TX
才能从 table 1.
以下是我试过的代码,
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"];
这是一个糟糕的数据模型。应该有一个单独的 table 来存储组和类别之间的关系,每个元组在不同的行上。 sticky bit 对问题的链接评论给出了关于如何以及为什么的很好的解释。
对于您当前的结构,一个选项使用 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