MYSQL根据另一个表

时间:2015-04-23 21:58:31

标签: php mysql sql

正如标题所示,我想基于另一个表中的列的值对一个表执行INSERT查询,以尝试创建等待列表类型系统。 这是我的代码:

$sql = "INSERT INTO bookings (username, tourDate, tourTime, tourNumber, guests) 
VALUES ('$username', '$tour_date', '$tour_time', '$tour_num', '$guests')";

$qry = "UPDATE tours
SET available = available-(1+$guests)
WHERE tourNum = '$tour_num'";

"INSERT INTO waitingList (username, tourDate, tourTime, tourNumber, guests) 
VALUES ('$username', '$tour_date', '$tour_time', '$tour_num', '$guests')";

我想要的是:

IF
available column in tours does not = 0
THEN
$sql
ELSE 
insert into waitingList 

'waitingList'是一个表格,其中包含与“预订”相同的字段

到目前为止,每次尝试都未能取得这些成果。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

要在表格上选择值并将其插入另一个表格,您可以使用此

INSERT INTO table1 (column_name1, column_name2)
SELECT column_name1, column_name2 FROM table2
WHERE column_name1 = "x";

答案 1 :(得分:1)

假设您正在使用PDO扩展,您应该尝试这样的事情:

<?php
$db = new PDO('mysql:Host=localhost;dbname=testdb;charset=utf8' , 'yourUserName', 'pw');
$stmt = $db->query("SELECT * FROM tours");
$rowCount = $stmt->rowCount();
if ($rowCount > 0) {
    $stmt = "INSERT INTO bookings 
    (username, tourDate, tourTime, tourNumber, guests) 
    VALUES ('$username', '$tour_date', '$tour_time', '$tour_num', '$guests')";
    $updateStmt = "UPDATE tours
    SET available = available-(1+$guests)
    WHERE tourNum = '$tour_num'";
    $query = $db->exec($stmt);
    $updateQuery = $db->exec($updateStmt);
}
else {
    $stmt = "INSERT INTO waitingList 
    (username, tourDate, tourTime, tourNumber, guests) 
    VALUES ('$username', '$tour_date', '$tour_time', '$tour_num', '$guests')";
    $query = $db->exec($stmt);
}

在SELECT查询中使用“*”有时不太好,即使这种方式有效,您也应该尝试使用更具体的字段,如表的主键。

答案 2 :(得分:1)

您需要为此使用innoDB表和事务。另外,我可以推荐PDO吗?

伪代码

qty = guests+1;

INSERT INTO bookings
Begin transaction
Select available from tours where tourNum = :tour_number
If selected available - qty <= 0
    update tours set available to 0 where tourNum = :tour_number
    insert into waiting list
else
    update tours set available to available-qty
endif
Commit Transaction