MySQL:只有在任何行的情况下

时间:2012-11-19 16:24:07

标签: mysql

                ->and_where_open()
                    ->and_where('orders.status', '=', 'delivered')->or_where('orders.status', '=', 'new')
                ->and_where_close()

这就是我得到的:

SELECT deals.*, SUM(orders.total_count) AS revenue, SUM(orders.quantity) AS qty
                FROM deals
                LEFT JOIN users ON (users.id = deals.partner_id)
                LEFT JOIN orders ON (orders.deal_id = deals.id)
                WHERE (orders.status = 'delivered' OR orders.status = 'new')
                AND (title LIKE '%cake%'
                        OR title LIKE '%cake%'
                        OR description LIKE '%cake%'
                        )
                AND deals.seller_id = 123
                GROUP BY deals.ID
                ORDER BY ID DESC
                LIMIT 10

如果有任何订单并且他们已交付状态或新状态,这种情况很有效。

我希望此查询显示所有交易,也包括那些没有订单的交易。

所以:如果这个deal_id存在订单,那么它应该执行SUM()并检查orders.status是交付还是新的,否则它现在应该仍然可以获得交易。相反,这个查询会排除交易行,而我仍然想要抓住它。

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您使用了LEFT JOIN代替INNER JOIN,如果没有订单,也可以提供记录。但是,因为您同时使用了WHERE子句中的orders表,所以您实际上构建了一个INNER JOIN。

您也可以通过将条件移动到连接来更改它,或者在where子句中添加一个附加内容,该子句还允许orders.orderid(或类似的,必填字段)is null的记录。

展示第一个:

SELECT deals.*, SUM(orders.total_count) AS revenue, SUM(orders.quantity) AS qty
            FROM deals
            LEFT JOIN users ON (users.id = deals.partner_id)
            LEFT JOIN orders ON (orders.deal_id = deals.id) AND
             (orders.status = 'delivered' OR orders.status = 'new')
            WHERE
               (title LIKE '%cake%'
                OR title LIKE '%cake%'
                OR description LIKE '%cake%'
               )
            AND deals.seller_id = 123
            GROUP BY deals.ID
            ORDER BY ID DESC
            LIMIT 10

展示第二个:

SELECT deals.*, SUM(orders.total_count) AS revenue, SUM(orders.quantity) AS qty
            FROM deals
            LEFT JOIN users ON (users.id = deals.partner_id)
            LEFT JOIN orders ON (orders.deal_id = deals.id)
            WHERE (
               orders.ID is null 
               or orders.status = 'delivered' 
               OR orders.status = 'new')
            AND (title LIKE '%cake%'
                    OR title LIKE '%cake%'
                    OR description LIKE '%cake%'
                    )
            AND deals.seller_id = 123
            GROUP BY deals.ID
            ORDER BY ID DESC
            LIMIT 10

我不知道您使用哪种ORM,但我认为第二种使用ORM通常更容易实现。

顺便说一下,您按ID订购,但没有使用别名。我不清楚(不是MySQL),如果是users.ID,orders.ID或deals.ID。