简体   繁体   English

SQL:将值插入外键

[英]SQL: insert value into foreign key

Im using phpmyadmin for a website i'm creating and have a question about a inserting values into foreign key. 我正在为我正在创建的网站使用phpmyadmin,并且对将值插入外键有疑问。

Im able to select an image table id when event col in events table is value x ie.. 当事件表中的事件col为x值时,无法选择图像表ID。

$event = "Partay";

$sql = "SELECT i.ImageID
FROM images i 
INNER JOIN events e 
ON i.eventID = e.eventID
WHERE e.event ='".$event."'";

This works for selecting images to display. 这适用于选择要显示的图像。 However when i want to insert and image inner join doesnt seem to work the same. 但是,当我要插入图像内部联接时,它似乎不起作用。

$sql = "INSERT INTO images i (i.image, e.event) 
INNER JOIN event e 
ON i.eventID = e.eventID
VALUES ('".$content."','".$event."')";

-Im trying to insert image into images table and a new event into event table so that this new image belongs to this new event. -我正在尝试将图像插入图像表中并将新事件插入事件表中,以便此新图像属于此新事件。 -Also how would inserting work when inserting image with an existing event? -在插入具有现有事件的图像时,如何进行插入工作?

Any help would be good thank you. 任何帮助都会很好,谢谢。

You should INSERT first the event, if Ok, then INSERT the image if it has any. 您应该先插入事件(如果确定),然后插入图像(如果有)。 Don't know, how you want to do that, but I think you should check if there is an insert or update that you want. 不知道您要怎么做,但是我认为您应该检查是否有想要的插入或更新。

In both situation you should use a transaction to ensure that you insert all that you want or not at all. 在这两种情况下,您都应使用事务来确保插入所有您想要或根本不需要的东西。 (Event and Image in this case). (在这种情况下为事件和图像)。

Read something about transaction and isolation level to understand this better. 阅读有关事务和隔离级别的知识,以更好地理解这一点。

Use two separate insert statements wrapped in a transaction. 使用包装在事务中的两个单独的插入语句。

To insert an image for an event which already exists, just use the insert statement for the image. 要为已存在的事件插入图像,只需对图像使用insert语句。

Invalid SQL Syntax. 无效的SQL语法。 There in no way to do it in one instruction in SQL. 用SQL的一条指令根本不可能做到这一点。

Insert in event, then insert in images. 插入事件,然后插入图像。 Use a transaction like swarFish said if you want to ensure atomicity (ensure that both are successful or no register is inserted). 如果要确保原子性(请确保两者均成功或不插入任何寄存器),请使用像swarFish这样的事务。

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

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