简体   繁体   English

php mysql使用join从2个表中显示/获取由ORDER_DATE分组的客户订购的所有产品

[英]php mysql display/get all the products ordered by the customer grouped by ORDER_DATE from 2 tables using join

I have these two tables CART and ORDERS . 我有这两个表CARTORDERS I would like to display/get all the products ordered by the customer grouped by ORDER_DATE how can I do this by Joining these two table? 我想显示/获取按ORDER_DATE分组的客户订购的所有产品,如何通过合并这两个表来做到这一点? or what is the correct code, script or syntax for it.. This is a 1:n relation I also want to display the items ordered by the customer ORDERED BY order_date.. 或正确的代码,脚本或语法是什么。.这是1:n关系,我也想显示客户订购的商品ORDERED BY order_date。

CART Table: CART表:

  • cart_id cart_id
  • product_id product_id
  • user_id 用户身份
  • prod_name prod_name
  • price 价钱
  • quantity 数量
  • image 图片

ORDER Table: ORDER表:

  • order_id order_id
  • cart_id cart_id
  • user_id 用户身份
  • total
  • customer_name 顾客姓名
  • order_date 订购日期

in case you are looking to list all the items ordered by order date (not grouped) then it would be like this: 如果您要列出按订购日期排序的所有商品(未分组),则可能是这样的:

SELECT * 
FROM `order` 
LEFT JOIN cart ON cart.cart_id=`order`.cart_id 
ORDER BY order_date ASC

or : 要么 :

SELECT * 
FROM cart 
LEFT JOIN `order` ON `order`.cart_id=cart.cart_id
ORDER BY order_date ASC

as from the structure it seems that cart can contain several orders (while order can not contain more carts) - that's where you must tell us, whether it is 1:n relation (of those two tables) or whether it's 1:1 (in which case you do not need the cart_id and can use the order_id instead as the linking element in both tables) 从结构上看,购物车似乎可以包含多个订单(而订单不能包含更多的购物车)-您必须在这里告诉我们这两个表中是1:n关系还是1:1(在在这种情况下,您不需要cart_id,而可以使用order_id作为两个表中的链接元素)

in case you want to "group" it somewhat, then you will have to sacrifice the detail (which is to be grouped together) grouping is useful, if you wanted to see the total values of all the orders - but doing so, you would only see the total value but NOT the items from each order (not in a line by line view) 万一您想对其进行“分组”,那么您将不得不牺牲细节(将其分组在一起),如果您想查看所有订单的总价值,分组是有用的-但是这样做,您将仅查看总计值,但不查看每个订单中的项目(不在逐行视图中)

EDIT: 编辑:
[ sorry i forgot.. it's a 1:n relation.. i also need to display the ordered items from each customer.. is that possible ? [对不起,我忘记了..这是1:n的关系..我还需要显示每个客户的订购商品..可以吗? :) ] :)]

in that case the structure does not seem very sound assuming the master table is the "order" then the table with detail should contain refference to the master table: 在那种情况下,假设主表是“ order”,则结构看起来并不健全,那么具有详细信息的表应包含对主表的引用:

CART Table: 购物车表:

  • cart_id cart_id
  • order_id (added) order_id (添加)
  • product_id product_id
  • user_id 用户身份
  • prod_name prod_name
  • price 价钱
  • quantity 数量
  • image 图片

ORDER Table: 订单表:

  • order_id order_id
  • cart_id (removed) cart_id (已删除)
  • user_id 用户身份
  • total
  • customer_name 顾客姓名
  • order_date 订购日期

Again your question isn't very clear. 同样,您的问题不是很清楚。 Do you want to see the items a user purchased grouped by the items (that is, if they buy a pencil today rubber tomorrow and another pencil the day after tomorrow, you will see two lines of result similar to: 您是否要查看用户购买的商品,并按商品分组(即,如果他们今天买了一支铅笔,明天又买了另一支铅笔,则您将看到两行类似的结果:

item   | qty
-------+----
pencil | 2  
rubber | 1

then use: 然后使用:

SELECT `order`.*, product_id, product_name, SUM(quantity) AS qty 
FROM `order` 
LEFT JOIN cart ON cart.order_id=`order`.order_id
GROUP BY product_id
ORDER BY product_name

Juan, this i getting really long and i'm not sure whether the Stack Overflow site is intended for this kind of dialog, but i'll try to explain once again. Juan,这我要花很长时间了,我不确定Stack Overflow网站是否适合这种对话框,但是我将尝试再次解释。 I will simplify your tables so the code i post here is simple. 我将简化您的表,以便在此处发布的代码很简单。

CREATE TABLE orders (
    orderID int unsigned not null auto_increment,
    user int unsigned not null,
    PRIMARY KEY (orderID)
);

CREATE TABLE orderitems (
    oiID int unsigned not null auto_increment,
    order int unsigned not null,
    item int unsigned not null,
    PRIMARY KEY (oiID)
);

The above is assuming that there is a table of users (Where is the user's name and email etc) and table of items (where the item names and item prices are). 上面假设有一个用户表(用户名和电子邮件地址在哪里)和项目表(项目名称和价格在哪里)。

I'm also assuming (wrongly, but for the sake of simplicity), that in my scenario noone will ever have the desire to buy more than 1 piece of any item i'm selling and noone will ever want to buy more than 3 items at the same time. 我还假设(错误地,但是为了简单起见),在我的情况下,没有人会愿意购买超过1件我要出售的商品,也没有人愿意购买超过3件商品与此同时。

Then my HTML entry form will be simple enough, because the user must be logged in when ordering (Thus i already know their userID - and it is held in my php $_SESSION['userID'] global variable), the order is always dynamically assigned at the time when user clicks CHECKOUT button (submits the form) and so the only thing we need the user to ENTER is the item ID (or rather pick it from a drop down list for example). 然后我的HTML输入表单就足够简单了,因为用户必须在订购时登录(因此我已经知道了他们的userID-并且它保存在我的php $ _SESSION ['userID']全局变量中),所以订单始终是动态的在用户单击CHECKOUT按钮时(提交表单)分配的,因此我们唯一需要用户输入的是项目ID(例如,而是从下拉列表中选择)。

so here is VERY SIMPLE entry form: 所以这是非常简单的输入表格:

<form action='orderit.php' method='post'>
    <select name='item[]'>
        <option value='' selected='selected'>Pick an item from the list!</option>
        <option value='1'>Knife</option>
        <option value='2'>Spoon</option>
        <option value='3'>Lava lamp</option>
        <option value='4'>HB pencil</option>
    </select><br/>
    <select name='item[]'>
        <option value='' selected='selected'>Pick an item from the list!</option>
        <option value='1'>Knife</option>
        <option value='2'>Spoon</option>
        <option value='3'>Lava lamp</option>
        <option value='4'>HB pencil</option>
    </select><br/>
    <select name='item[]'>
        <option value='' selected='selected'>Pick an item from the list!</option>
        <option value='1'>Knife</option>
        <option value='2'>Spoon</option>
        <option value='3'>Lava lamp</option>
        <option value='4'>HB pencil</option>
    </select><br/><br/>
    <input type='submit' value=' Checkout ' name='do'/>
</form>

From the above you see than when when user clicks checkout all the data (namely the choices the customer made are sent to the action which is set to orderit.php . Please note that i am not bothered about making sure the user is submiting valid information and i'm not using the latest technology (that being msqli) instead i'm using the deprecated mysql routines. 从上面的你比时,当用户点击结帐的所有数据(即由客户发送到的选择看action被设置为orderit.php 。请注意,我不打扰关于确保用户submiting有效信息而且我没有使用最新的技术(即msqli),而是使用了已弃用的mysql例程。

So here it follows: 因此,它如下所示:

<?php
     //here you will have your database opened, session initiated and so on
     // $db contains the database connection handler
     // $_POST['userID'] contains valid user's id

     if (isset($_POST['item']) && count($_POST['item'])>0) {
         //they ordered something we can create the order
         $q=mysql_query("INSERT INTO orders SET user='".mysql_real_escape_string($_SESSION['userID'])."'",$db);
         if (!$q)
             die("An error while creating new order");
         $orderID=mysql_insert_id($db); //fetch the just-now created order's ID
         foreach($_POST['item'] as $item) { //go through all the ordered items
            $q=mysql_query("INSERT INTO orderitems SET order='$orderID', item='".abs((int) $item)."'");
            if (!$q)
                die("Couldn't save item $item of order #$orderID");
         }
         print "Your order was saved successfuly!";
     } else
         die("This is an empty order");
?>

And that's all. 就这样。

Please note that i am writing this code from top of my head now, so there may be typos or other types of error. 请注意,我现在是从头开始编写此代码,因此可能存在输入错误或其他类型的错误。 take it more as an approximate guide rather than as a working piece of code. 将其更多地作为一个大概的指南,而不是作为一个有效的代码。

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

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