在php中组合多个sql查询

时间:2014-08-26 11:04:52

标签: php mysql sql

所以,我帮助了一个有票务系统的朋友参加慈善活动。在此页面上,用户可以选择他们想要的票数,然后点击"注册"。没有付款,他们可以只注册门票。票证有两种类型:普通票和贵宾票。

我创建了三个数据库:客户,门票和customer_tickets。以下是这些表的转储。

客户:

CREATE TABLE `customers` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `surname` varchar(2056) NOT NULL,
  `lastname` varchar(2056) NOT NULL,
  `email` varchar(2056) NOT NULL,
  `street` varchar(2056) NOT NULL,
  `house` int(255) NOT NULL,
  `postal` varchar(2056) NOT NULL,
  `city` varchar(2056) NOT NULL,
  `desired_vip_tickets` int(1) NOT NULL DEFAULT '0',
  `desired_normal_tickets` int(1) NOT NULL DEFAULT '0',
  `order_id` varchar(2056) NOT NULL,
  `status` varchar(2056) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;

Customer_tickets:

CREATE TABLE `customer_tickets` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `order_id` int(255) NOT NULL,
  `ticket_id` int(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

门票:

CREATE TABLE `tickets` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(2056) NOT NULL,
  `ticket_type` int(255) NOT NULL,
  `bought` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

当用户点击注册时,执行以下代码。但是,只执行第一个查询而不执行其他查询。另外,我担心如果所有这些查询都会让服务器受损......

$sql = "UPDATE customers SET `status`='$status' WHERE `order_id`='$order_id'";
$qry = mysql_query($sql) or die (mysql_error());

$sql = "SELECT `desired_vip_tickets`, `desired_normal_tickets` FROM customers WHERE `order_id`='$order_id'";
$qry = mysql_query($sql) or die (mysql_error());
$array = mysql_fetch_array($qry);

$vip = $array[0];
$normal = $array[1];

$sql = "SELECT `ticket_id` FROM tickets WHERE `ticket_type`='1' AND `bought`='0' LIMIT ".$vip;
$qry = mysql_query($sql) or die (mysql_error());

while ($row = mysql_fetch_assoc($qry)) {
    $ticket_id = $row['ticket_id'];

    $ins = "INSERT INTO customer_tickets (`order_id`, `ticket_id`) VALUES ('$order_id', '$ticket_id)";
    $query = mysql_query($ins) or die (mysql_error());

    $upd = "UPDATE tickets SET `bought`='1' WHERE `ticket_id`='$ticket_id";
    $query = mysql_query($upd) or die (mysql_error());
}

$sql = "SELECT ticket_id FROM tickets WHERE `ticket_type`='0' AND `bought`='0' LIMIT ".$normal;
$qry = mysql_query($sql) or die (mysql_error());

while ($row = mysql_fetch_assoc($qry)) {
    $ticket_id = $row['ticket_id'];

    $ins = "INSERT INTO customer_tickets (`order_id`, `ticket_id`) VALUES ('$order_id', '$ticket_id)";
    $query = mysql_query($ins) or die (mysql_error());

    $upd = "UPDATE tickets SET `bought`='1' WHERE `ticket_id`='$ticket_id";
    $query = mysql_query($upd) or die (mysql_error());
}

1 个答案:

答案 0 :(得分:0)

您需要SQL连接不同的表。你的SQL必须看起来像这样:

SELECT * FROM table1.customer_name, table2.amount_spent, recentpurchases
WHERE table2.amount_spent = recentpurchases.spendamount

我已经使用了这个anser的示例表。它们是table1,table2和recentpurchases。如果这不是一个有用的答案,请道歉。