开发者

Selecting rows that corresponds from other table

I have a product table that stores all products. Also I have a production table that stores productions.

I am using CodeIgniter and datamapper ORM.

Here is tables:

CREATE TABLE I开发者_如何学GoF NOT EXISTS `products` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `kod_stok` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `kod_lokal` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `kod_firma` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `firma` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fabrika` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `proje` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `tanim` mediumtext COLLATE utf8_unicode_ci,
  `saatlik_uretim` int(11) NOT NULL,
  `status` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `kod_lokal` (`kod_lokal`),
  KEY `kod_firma` (`kod_firma`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;

CREATE TABLE IF NOT EXISTS `productions` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `fabrika` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `board_no` int(11) NOT NULL,
  `date` int(11) DEFAULT NULL, // Unix Timestamp
  `operator_id` int(11) DEFAULT NULL,
  `product_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `product` (`product_id`),
  KEY `date` (`date`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;

I am trying to get count of production of given day. But not all products, producting everyday. I need to exlude the products that has 0 count.

$p = new Product();
$p->include_related_count('production');
$p->get();

And I want to add a date interval to production.

Basicly, I want to get all product's production count within a given day.

How can I do that?

Thank you for any advices.


Not sure about codeigniter details, but the following SQL query will generate a production list per day.

To get today's production:

$query = $this->db->query("
SELECT 
  a.count(*) as produced
  , a.product_id
  , b.kod_stok as productname
  FROM productions a
  INNER JOIN products b ON (a.product_id = b.id)
  WHERE FROM_UNIXTIME(a.date) = CURDATE()
  GROUP BY TO_DAYS(FROM_UNIXTIME(a.date)), a.product_id
");

To get last 7 days production

$query = $this->db->query("
SELECT 
  a.count(*) as produced
  , a.product_id
  , b.kod_stok as productname
  FROM productions a
  INNER JOIN products b ON (a.product_id = b.id)
  WHERE FROM_UNIXTIME(a.date) 
    BETWEEN DATE_SUB(CURDATE(),INTERVAL 7 DAY) AND CURDATE()
  GROUP BY TO_DAYS(FROM_UNIXTIME(a.date)), a.product_id
");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜