簡體   English   中英

如何根據外鍵從表中獲取多個值?

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

我有兩張桌子,

#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包含以下數據結構

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

從表 2 中,我可以使用查詢獲取 payroll_cat_name 的值

$a = "Select payroll_cat_name from table_2";

使用上面的查詢,我得到了值PF,HM,BP,TX

現在,我必須使用多個值PF,HM,BP,TX才能從表 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"];

這是一個糟糕的數據 model。 應該有一個單獨的表來存儲組和類別之間的關系,每個元組在不同的行上。 由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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM