运行此查询的最佳方式是什么?如何在MySQL中的两个表上同时执行两条select语句使用PHP
我在同一个数据库,产品和shop_orders中有两个表。我试图运行两个select语句,使用shop_orders的一个字段来检索数据。
<td align="center" bgcolor="#F5F5F5" class="column-light"><strong>Chain Men's Shoes</strong></td>
<td align="center" bgcolor="#F5F5F5" class="column-light"><strong>
<?
$sql="
SELECT * FROM shop_orders WHERE
DATE(CONCAT(shop_order_year,'-',shop_order_month,'-',shop_order_day))
BETWEEN '".$start."' and '".$end."'
AND shop_order_action = 'Sale' AND shop_order_field_to_update NOT LIKE '%con%' AND shop_order_location = 'Chain' ORDER BY shop_order_id DESC";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){ ?>
<? $shop_order_product_id = $rows['shop_order_product_id'];?>
<?
$sql2="SELECT * FROM product WHERE product_id='".$rows['shop_order_id']."' AND category = 'Mens'";
$result2=mysql_query($sql2);
$mens_shoes=mysql_num_rows($result2);
echo $mens_shoes; ?>
</strong></td> <?
}
?>
DB Structure
Product
Product ID Category
1234 Mens
2345 Mens
Shop_orders
shop_order_day shop_order_month shop_order_year shop_order_action
1 03 2014 Sale
shop_order_product id shop_order_field_to_update
1234 quantity_c_size_39
类似的字段是shop_order_product_id和Product ID。
此查询应该总计给定日期期间的销售数量,其中匹配标准为location,action = Sale且类别为Mens。这个查询的第一部分($ sql)已经有效,但是,当我尝试将它与第二个嵌入式SELECT语句结合使用时,返回的数字为零。我知道这个数字应该大于零。
任何帮助?
* UPDATE *
我似乎解决了这个问题:
$sql="
SELECT COUNT(*) FROM shop_orders
LEFT JOIN product
ON shop_orders.shop_order_product_id=product.product_id
WHERE
DATE(CONCAT(shop_order_year,'-',shop_order_month,'-',shop_order_day))
BETWEEN '".$start."' and '".$end."'
AND category = 'Mens' AND shop_order_action = 'Sale' AND shop_order_field_to_update NOT LIKE '%con%' AND shop_order_location = 'Chain' GROUP BY shop_order_id";
你为什么把订单日期分成几份单独的年份,月份和日期字段? –
在我之前创建数据库的人像这样设置它... – Aphex22