简体   繁体   English

根据另一个表中的另一个特定值在SQL表中插入ID

[英]Insert id in sql table based on another particular value in another table

I am stuck in a situation wherein I have to insert id in sql table based on another particular value in another table. 我陷入一种情况,我必须基于另一个表中的另一个特定值在sql表中插入id。

For example: I have one table say bookings with column invoice_number and another table say invoice_hotels with column invoice_id . 例如:我有一个表发言权列INVOICE_NUMBER和另一个表预订说与列INVOICE_ID invoice_hotels。

I am trying to insert invoice_id in invoice_hotels based on data in invoice_number column of bookings table. 我想基于在预订表的INVOICE_NUMBER列数据中invoice_hotels插入INVOICE_ID。

I want to achieve below functionality also use MySQL squery only not PHP 我想实现以下功能也只使用MySQL squery而不是PHP

  • If Last value in invoice_number column of bookings table is 9000 then I want to insert 9001 in invoice_id column of invoice_hotels 如果预订表的INVOICE_NUMBER列尾值是9000,然后我想在invoice_hotelsINVOICE_ID柱插入9001

I know this can easily be done through PHP script but I am trying to do it with sql only. 我知道可以通过PHP脚本轻松完成此操作,但是我尝试仅使用sql进行操作。

I have referred this and this but didn't understood how to use it. 我已经提到这个这个 ,但没有明白如何使用它。

You can try this query: 您可以尝试以下查询:

here we are geting max id for invoice_number and then will +1 increment with help of select query after that you can insert this value to another table with help of insert query. 在这里,我们获得发票编号的最大ID,然后在选择查询的帮助下将+1递增,之后您可以在插入查询的帮助下将该值插入到另一个表中。

INSERT INTO table_name ( field1, field2,...fieldN )                       
 VALUES((SELECT IFNULL(MAX(invoice_number)+1, 1) from bookings), value2,...valueN);

IFNULL(MAX,1) meaning if id is null then it will take by default id=1 IFNULL(MAX,1)表示如果id为null,则默认为id = 1

NOTE : I'm not sure about tablename and column name so you can adjust according your requirement. 注意 :我不确定表名和列名,因此您可以根据需要进行调整。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM