[英]MYSQL Insert a primary key in another table as foreign key
I'm trying to add a few Primary Keys from different tables as Foreign Keys to one Main table in a Query in php. 我试图将不同表中的一些主键作为外键添加到php中的一个查询主表中。
So far I got: 到目前为止,我得到了:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, 123, 123, '".$_SESSION['sId']."' , 123, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', 123,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."')");
Every "123" I want to replace with an existing Primary key from other tables from my database. 我想用数据库中其他表中现有的主键替换每个“ 123”。 How is this possible ? 这怎么可能 ?
You can use the INSERT ... SELECT
syntax. 您可以使用INSERT ... SELECT
语法。
Something like this where anotherTable
is the other table you want to insert from. 诸如此类,其中anotherTable
是要从中插入的另一个表。
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar) "
. "SELECT (DEFAULT, anotherTable.id, anotherTable.id, '".$_SESSION['sId']."' , anotherTable.id, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', anotherTable.id,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."') FROM anotherTable");
If needed you can also limit the number of inserted rows into m_main
with a WHERE
clause in the SELECT
statement. 如果需要,您还可以使用SELECT
语句中的WHERE
子句限制插入m_main
行数。
A long time ago I asked this question. 很久以前我问了这个问题。 Finally I found some time to answer it in case anybody has the same problem. 最后,如果有人遇到相同的问题,我花了一些时间来回答。 Don't know why I wanted to make it so complicated. 不知道为什么我要使它变得如此复杂。 Subquerys where the answer: 子查询的答案在哪里:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, (SELECT MAX id FROM title), (((AND SO ON...)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.