如何创建sql_query

时间:2013-08-19 20:39:49

标签: php mysql

我已经在php.3中创建了一些过滤器,它们正在调整1个表。第四个是另一张桌子。 第一个表是:

id_of_orders :
id_order(int) time(NOW) username(varchar) price(decimal)

第二个是:

order :
 order_id(int)  product(varchar) price (decimal)

order.order_id是指id_of_orders.id_order

表id_of_orders就像订单表的映射器(id_of_orders.id_order具有唯一编号)。 表订单包含许多订单,其中一些订单具有相同的order_id

我想返回包含order.product=='proion'

的id_of_orders.id_order

我使用的查询是:

$query = "SELECT * FROM id_of_orders WHERE 1=1";
if(!empty($_SESSION['employees']))
  $query .= " AND id_of_orders.username='$_SESSION[employees]'";
if(!empty($_SESSION['timis']))
  $query .= " AND id_of_orders.price='$_SESSION[timis]'";
if(!empty($_SESSION['dates']))
  $query .= " AND DATE(time)='$_SESSION[dates]'";
//if(!empty($_SESSION['proions']))
 // $query .= " AND (orders.product='$_SESSION[proions]' && id_of_orders.id_order==orders.order_id)";

$result = mysql_query($query);

1 个答案:

答案 0 :(得分:1)

您可以尝试像

这样的查询
SELECT o.* 
  FROM id_of_orders i JOIN
(
  SELECT order_id
    FROM orders
   WHERE product = 'proion'
   GROUP BY order_id
) q ON i.id_order = q.order_id
 WHERE o.username = ?
   AND o.price = ?
   AND DATE(time) = ?

SELECT i.id_order, i.time, i.username, i.price 
  FROM id_of_orders i JOIN orders o
    ON i.id_order = o.order_id
 WHERE 1 = 1
   AND o.product = 'proion'
   AND o.username = ?
   AND o.price = ?
   AND DATE(time) = ?
 GROUP BY i.id_order, i.time, i.username, i.price