如何在php mysql中显示商店名称代替分支名称

时间:2019-05-16 16:19:39

标签: php mysql mysqli

我有一个名为“ tbl_stores”和“ tbl_deals”的mysql表。基本结构看起来像这样-

mysqltable

我想在同一表中按商店ID和分支ID显示商店名称而不是分支名称

我尝试了获取存储和分支名称的以下代码

<div class="modal inmodal" id="modal_div" tabindex="-1" role="dialog"  > 
  <!-- content -->
</div>

1 个答案:

答案 0 :(得分:0)

您需要将tbl_stores与自身结合起来,才能从分支机构获取相关商店。

$sql1 = "SELECT  t1.s_id,t1.p_id,t3.store_name,t1.store_address,t1.store_city,t1.store_lat,t1.store_lng,t1.store_cat,t1.store_status,t2.deal_name,t2.deal_desc,t2.deal_end,t2.deal_type,t2.deal_m,t2.deal_n,t2.deal_op,t2.deal_dp,t2.deal_pf,t2.deal_pa,t2.deal_sa,t2.deal_fi, t2.deal_images, t2.deal_stores,t2.deal_status 
FROM tbl_stores t1
CROSS JOIN tbl_deals t2 
JOIN tbl_stores t3 ON t1.p_id = t3.s_id
WHERE t1.s_id=$s_id and t2.d_id=$d_id";

如果$s_id可以成为主要商店而不是分支机构,则可以使用LEFT JOINIFNULL()来处理这种情况。

$sql1 = "SELECT  t1.s_id,t1.p_id,IFNULL(t3.store_name, t1.store_name) AS store_name,t1.store_address,t1.store_city,t1.store_lat,t1.store_lng,t1.store_cat,t1.store_status,t2.deal_name,t2.deal_desc,t2.deal_end,t2.deal_type,t2.deal_m,t2.deal_n,t2.deal_op,t2.deal_dp,t2.deal_pf,t2.deal_pa,t2.deal_sa,t2.deal_fi, t2.deal_images, t2.deal_stores,t2.deal_status 
FROM tbl_stores t1
CROSS JOIN tbl_deals t2 
LEFT JOIN tbl_stores t3 ON t1.p_id = t3.s_id
WHERE t1.s_id=$s_id and t2.d_id=$d_id";