显示来自另一个表的畅销商品和相关图像

时间:2016-04-13 09:42:43

标签: php mysql oop

我想在索引页面上显示4个畅销商品的图片,但我使用的sql不起作用。我认为语法是正确的,但不会在页面上显示任何内容。我有一个 order_items表产品表

产品表

  CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL,
  `date` datetime NOT NULL,
  `category` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `image` varchar(100) CHARACTER SET utf8 NOT NULL,
  `description` text NOT NULL,
  `author` varchar(100) NOT NULL,
  `price` decimal(5,2) NOT NULL
   ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;

Order_items表

  CREATE TABLE IF NOT EXISTS `order_items` (
  `id` int(11) NOT NULL,
  `order` int(11) NOT NULL,
  `product` int(11) NOT NULL,
  `price` decimal(8,2) NOT NULL,
  `qty` int(11) NOT NULL
  ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;

注意:在order_items表中,字段产品对应于产品的ID。

最后,这是我使用的sql语句,但没有显示任何内容。

   public function bestSellingItems(){
    $sql = "SELECT * FROM products AS p 
   INNER JOIN order_items AS od ON p.id = od.id 
   GROUP BY p.id, SELECT SUM(od.qty) AS total
   ORDER BY SUM(od.qty) DESC limit 4";
}

我将不胜感激。

2 个答案:

答案 0 :(得分:0)

你说的是你自己,product对应id而你使用了p.id = od.id,我也不理解第二个选择中我认为会引发错误的部分(不是..)所以我稍微调整了一下 - 选择总和,别名并按别名排序。

   public function bestSellingItems(){
    $sql = "SELECT p.*,od.*,sum(od.qty) as sum_qty FROM products AS p 
   INNER JOIN order_items AS od ON p.id = od.product 
   GROUP BY p.id
   ORDER BY sum_qty DESC limit 4";
}

答案 1 :(得分:0)

您的加入“INNER JOIN order_items AS od ON p.id = od.id ”应为INNER JOIN order_items AS od ON p.id = od.Product < / p>