简体   繁体   中英

CodeIgniter: Join more than 3 tables

I have five tables:

  1. Bill : no(pk),date, time, total
  2. BillOrderRelation : no(fk), order_id(fk)
  3. Order : order_id(pk), menu_id(fk), quantities, total
  4. Menu : menu_id(pk), category_id(fk), menu_name, stock, price
  5. Category : category_id(pk), category_name, colour

In my case, I have to retrieve which menu that has a highest sales in one day range, 7 days range, and 30 days range.

I've already succeed retrieve those information, but i think it's too complicated. First I have to retrieve the date on Bill, and then find the order in BillOrderRelation, and then find the Menu, and find the Category name. It includes a lot of queries and complex way to do the summing stuff for the same menu.

My question is, is that possible to query all those table in one query to retrieve just menu.menu_name, order.quantities, order.total, category.name and it's included the sum stuff for the same menu retrieved?

I've already succeed make a query for three table without using time range like this..

SELECT 
    menu.menu_name as top_item, 
    SUM(order.quantities) AS count_sold, 
    SUM(order.total) AS amount, 
    category.nama AS categories 
FROM 
    menu, order, category 
WHERE 
    menu.mennu_id = bill.menu_id 
    AND category.category_id = menu.category_id 
GROUP BY 
    bill.menu_id, menu.menu_name, category.category_name 
ORDER BY 
    count_sold DESC

Is there any tricky way for the case above?

Update for PostgreSQL

I believe you want something like this:

SELECT
    m.menu_name AS top_item
    , c.name AS category
    , SUM(o.quantities) AS sum_quantity
    , SUM(o.total) AS sum_total
FROM
    menu m
JOIN
    category c
    ON c.category_id=m.category_id
JOIN
    order o
    ON o.menu_id=m.menu_id
JOIN
    billorderrelation bor
    ON bor.order_id=o.order_id
JOIN
    bill b
    ON b.no=bor.no
WHERE
    b.date >= (CURRENT_DATE - INTERVAL '7 days')
GROUP BY
    m.menu_id
ORDER BY
    sum_quantity DESC
;

CURRENT_DATE allows you to get the current date (according to the timezone specified in your database). Read more: https://www.postgresql.org/docs/8.2/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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