简体   繁体   English

如何:插入值在另一个表上的列中

[英]How To: Insert into column where the value is on another table

Summarize the Problem:总结问题:

I want to write a booking code .我想写一个预订代码 I had a little problem, that I wanted to insert a value into the booked table that is in another table called house_info .我有一个小问题,我想在另一个名为house_info表中的booked表中插入一个值。

The detail of booked & house_info database is below: booked & house_info数据库的详细信息如下:

Booked Table预定桌位

 ID_Booking | House_Name | House_ID | House_No | House_Qty | House_Price |
          1 | Rose House |        1 |     RH01 |         1 |             |
          2 | Rose House |        1 |     RH02 |         1 |             |

House Info Table房屋信息表

 House_ID | HouseState_Name | House_Qty | House_Price |
        1 |     Garden City |         8 |        40000|
        2 | Electronic City |        10 |      1000000|

I want to insert the House_Price value on the house_info table into the House_Price column on booked table every time users input on the Booking Form .我想在插入House_Price上的值house_info表到House_Price柱上booked预订表上的用户每次输入。

Background you've already tried:您已经尝试过的背景:

I already tried this using a trigger on booked table like below:我已经在booked桌子上使用触发器尝试过这个,如下所示:

Trigger on Booked Table (Before Insert)在预订表上触发(插入前)

IF NEW.House_ID= '1' THEN SET
NEW.House_Price = 40000;
ELSEIF NEW.House_ID= '2' THEN SET
NEW.House_Price = 1000000;

But I realize this is not dynamic because when the company want to change the price of each HouseState_Name he needs to change it from the trigger.但我意识到这不是动态的,因为当公司想要更改每个HouseState_Name的价格时,他需要从触发器中更改它。 So I think what I needed is a query from PHP that can calls the value of each HouseState_Name and hold it on an array and place it or insert it when the Book Query passed (I hope my logic is true, I'm sorry if it's false).所以我认为我需要的是来自PHPquery ,它可以调用每个HouseState_Name的值并将其保存在一个array并在Book Query传递时将其放置或插入(我希望我的逻辑是正确的,如果它是,我很抱歉错误的)。

I already tried to search too for the query 's to use.我已经尝试过搜索要使用的query But I didn't know how am I going to use the query.但我不知道我将如何使用查询。

Some Codes:一些代码:

Booking.php预订.php

require 'Connection.php';

//Check Connection
if ($conn->connect_error){
    die("Connection Failed: ". $conn->connect_error);
}

//Check for Submit
if (filter_has_var(INPUT_POST, 'Submit')) {
    //Get Form Data
    $CustomerEmail= htmlspecialchars($_POST["Email"], ENT_QUOTES);
    $House_Name= htmlspecialchars($_POST["HouseName"], ENT_QUOTES);
    $House_ID = htmlspecialchars($_POST["HouseID "], ENT_QUOTES);
    $House_No = htmlspecialchars($_POST["HouseNo "], ENT_QUOTES);

    //Validate the data fields
    if (!empty($CustomerEmail) && !empty($House_Name)) {
        //Passed
        if (filter_var($CustomerEmail, FILTER_VALIDATE_EMAIL) === false) {
            //Failed
            $msg = 'Please use a valid email';
            header("location: ../GardenCity.php?error=PleaseUseValidEmail");
        } else {
            //Passed
            echo "Creating a Booking.<br>";
            //Inserting the Booking Data into Database
            $sql = "INSERT INTO `booked`(`ID_Booking`, `CustomerEmail`, `House_Name`, `House_ID`, `House_No`) 
            VALUES (NULL, '$CustomerEmail', '$House_Name', '$House_ID ', '$House_No', '', '')";
            if ($conn->query($sql) === TRUE) {
                header("location: ../GardenCity.php");
            } else {
                echo "Error: " . $sql . "<br><br>" . $conn->error;
            }
        }

    } else {
        header("location: ../GardenCity.php?error=EmptyFields");
    }

}

$conn -> close();

Expected Results:预期成绩:

Before Update the price更新价格前

Database Looks数据库外观

ID_Booking | House_Name | House_ID | House_No | House_Qty | House_Price | 1 | Rose House | 1 | RH01 | 1 | | 2 | Rose House | 1 | RH02 | 1 | | 3 | Rose House | 1 | RH03 | 1 | 40000|

House_ID | HouseState_Name | House_Qty | House_Price | 1 | Garden City | 7 | 40000| 2 | Electronic City | 10 | 1000000|

After Update the price更新价格后

Database Looks数据库外观

ID_Booking | House_Name | House_ID | House_No | House_Qty | House_Price | 1 | Rose House | 1 | RH01 | 1 | | 2 | Rose House | 1 | RH02 | 1 | | 3 | Rose House | 1 | RH03 | 1 | 40000| 4 | Rose House | 1 | RH04 | 1 | 200000|

House_ID | HouseState_Name | House_Qty | House_Price | 1 | Garden City | 6 | 200000| 2 | Electronic City | 10 | 1000000|

I hope this is well explained.我希望这能得到很好的解释。 Please let me know if there's any confusing statements or questions.如果有任何令人困惑的陈述或问题,请告诉我。 I will say many thanks to you all if this is answered because I'm so stuck at this and my brain won't work.如果这个问题得到解答,我会非常感谢你们,因为我被困在这个问题上,我的大脑无法工作。

I think this could work, basically using a subquery just to fetch the price, that should achieve the same result as your insert trigger, but without using fixed prices.我认为这可以工作,基本上只使用子查询来获取价格,应该获得与插入触发器相同的结果,但不使用固定价格。

INSERT INTO `booked` (
   `ID_Booking`, 
   `CustomerEmail`,
   `House_Name`, 
   `House_ID`,
   `House_No`, 
   `House_Qty`, 
   `House_Price`
) VALUES (
    NULL, 
   '$CustomerEmail', 
   '$House_Name', 
   '$House_ID',
   '$House_No', 
   '1', 
   (SELECT House_Price FROM house_info WHERE House_ID = '$House_ID')
)

Edit: I set House_Qty at 1, change it according to your needs :)编辑:我将House_Qty设置为 1,根据您的需要进行更改:)

Maybe you can use the same subquery in your trigger directly instead (haven't tested it) :也许您可以直接在触发器中使用相同的子查询(尚未测试):

SET NEW.House_Price = 
   (SELECT House_Price FROM house_info WHERE House_ID = NEW.House_id);

Assuming your House_ID are unique :)假设您的House_ID是唯一的 :)

I would expect to see a schema more or less like this:我希望或多或少会看到这样的模式:

houses(house_id*,name)

house_prices(house_id*,price_start_date*,price)

bookings(booking_id*,customer_id,total)

booking_detail(booking_id*,house_id*,start_date,end_date)

* = (component of) PRIMARY KEY

After some reflection, it should be apparent that your present concerns evaporate with this design.经过一些思考,很明显,您目前的担忧会因这种设计而消失。

You can construct such an UPDATE statement with INNER JOINs one of which's in the subquery as a self-JOIN for booked table, put after your existing INSERT statement :您可以使用INNER JOINs构造这样一个UPDATE语句,其中一个在子查询中作为booked表的self-JOIN ,放在现有的INSERT语句之后:

update house_info h join (
  select b1.House_Price, b2.House_ID
  from booked b1
  join ( select House_ID,max(ID_Booking) as ID_Booking 
                from booked
               group by House_ID
                ) b2
     on b1.House_ID = b2.House_ID and b1.ID_Booking = b2.ID_Booking   
) bb on bb.House_ID = h.House_ID
set h.House_Price = bb.House_Price;

but I should admit that your tables' design is not good, because of repeating columns they hold the same information in each.但我应该承认你的表格设计不好,因为重复的列它们在每个中都包含相同的信息。

Demo 演示

Insert Into booked_table (ID_Booking, House_Name, House_Id, House_No, House_Qty, House_Price)
Select 1, House_Name, House_ID, 'RHXX', House_Qty, (SELECT House_Price FROM house_info WHERE House_ID = MM1.House_ID) From booked_table MM1
Where
NOT EXISTS(
  SELECT * 
  FROM booked_table MM2
  WHERE MM2.ID_Booking > MM1.ID_Booking
);

Fiddle: https://www.db-fiddle.com/f/7Bt3ZTQqbjs1jKzJe34qSF/0小提琴: https : //www.db-fiddle.com/f/7Bt3ZTQqbjs1jKzJe34qSF/0

I dont included the increment of the ID_Booking and House_No.我不包括 ID_Booking 和 House_No 的增量。 If you want to increase the House_Price, just do that with another query.如果您想增加 House_Price,只需使用另一个查询即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在INSERT的另一列的值中使用表列的动态值 - How to use dynamic value of table column in the value of another column on INSERT 如何在表的列中插入另一个表的COUNT值 - How to insert COUNT value of another table in column of a table 如何根据另一个表的选择在表的列中插入值 - How to insert value in a column of a table based on a selection of another table 在插入的另一个表中更改另一个列的值 - Changing another column value in another table on an insert 根据列值将行插入另一个表 - Insert rows into another table based on column value 根据另一列的值将值插入新表的列中 - Insert value into column in new table based on value from another column 如何设置表中的一列,而另一表中的列具有特定值? - How can I set one column in a table where a column in another table has a certain value? 如何将值添加到列字段中的现有值,然后将更新值插入另一个表 - How to add a value to already existing value in column field and then insert the update value into another table MySQL多插入从另一个表中选择多列 - mysql multiple Insert where select many column from another table 在插入MySQL表时,如何将自动递增ID列的值插入另一列? - How do I insert the value of an auto-increment ID column into another column on inserting into MySQL table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM