简体   繁体   English

从mysql中的多个表中检索值

[英]retrieving values from multiple tables in mysql

I am using php and I have to get the data from multiple tables with common id, but the problem is that in few tables that common id contains multiple records,using inner join gives me separate rows of data eg 我正在使用php,我必须从具有公共ID的多个表中获取数据,但是问题是在少数具有公共ID的表中,使用内部联接可以给我单独的数据行,例如

{"dish_id":"52","quantity":"1","STATUS":"pending","franchise_id":"5","order_type":"PickUp","extraId":"2"}
    {"dish_id":"52","quantity":"1","STATUS":"pending","franchise_id":"5","order_type":"PickUp","extraId":"3"}

extraId is the multiple record for the dish_id:52. extraId是dish_id:52的多重记录。 I need result like this. 我需要这样的结果。

{"dish_id":"52","quantity":"1","STATUS":"pending","franchise_id":"5","order_type":"PickUp","extraId"[{"id":"2"},{"id":"3"]}}

My query is: 我的查询是:

 $orders =  "Select DISTINCT order_detail.dish_id,order_detail.quantity,order_detail.STATUS,
order_main.franchise_id,order_main.order_type,
order_extras.extra_id,order_extras.extra_title,
order_addons.addon_id,order_addons.addon_size 
from order_main 
INNER JOIN order_detail ON order_main.id=order_detail.order_id 
INNER JOIN order_extras ON order_main.id=order_extras.order_id 
INNER JOIN order_addons ON order_main.id=order_addons.order_id 
WHERE order_main.franchise_id='$storeId' 
and 
order_detail.STATUS!='$order_status'";

please help. 请帮忙。

Use group by and group_concat . 使用group bygroup_concat Something like this: 像这样:

Select d.dish_id, d.quantity, d.STATUS, m.franchise_id, m.order_type,
       group_concat(e.extra_id) as extraids
from order_main m INNER JOIN
     order_detail d
     ON m.id = d.order_id INNER JOIN
     order_extras e
     ON m.id = e.order_id INNER JOIN
     order_addons a
     ON m.id = a.order_id 
where m.franchise_id = '$storeId' and d.STATUS <> '$order_status'
group by d.dish_id, d.quantity, d.STATUS, m.franchise_id, m.order_type;

Your desired results do not include these columns: 您想要的结果不包括以下列:

  • e.extra_title
  • a.addon_id
  • a.addon_size

I would also suggest that you remove the join to order_addons . 我还建议您删除对order_addons的连接。

Notice that table aliases make the query easier to write and to read. 请注意,表别名使查询更易于编写和阅读。

You can use group by with dish_id 您可以将group bydish_id一起dish_id

$orders =  "Select DISTINCT order_detail.dish_id,order_detail.quantity,order_detail.STATUS,
order_main.franchise_id,order_main.order_type,
order_extras.extra_id,order_extras.extra_title,
order_addons.addon_id,order_addons.addon_size 
from order_main 
INNER JOIN order_detail ON order_main.id=order_detail.order_id 
INNER JOIN order_extras ON order_main.id=order_extras.order_id 
INNER JOIN order_addons ON order_main.id=order_addons.order_id 
WHERE order_main.franchise_id='$storeId' 
 and 
order_detail.STATUS!='$order_status' group by order_detail.dish_id";

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

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