我正在尝试将数据插入到库存表中,从单独的Users表中提取UserID以填充其中一个字段。
Inventory:
ProductID | PurchasedByUser | OtherAttributes
和用户表;
Users:
DBID | UserActive | UserName
1 | 1 | mathew
到目前为止我的SQL看起来像:
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT 23, U.DBID, 'Yellow'
FROM Inventory U INNER JOIN Users ud
ON U.DBID = ud.DBID AND ud.UserActive = 1 AND UserName = 'mathew'
编辑: 我希望能够添加一个SQL INSERT请求 ProductID(INT),PurchasedByUser(Users.DBID),OtherAttributes(String)到Inventory表,不暴露DBID并仅传递UserName字段。
答案 0 :(得分:1)
在查询中U.DBID
错误,因为U
是广告资源的别名所以请更改并放置ud.DBID
,您的查询将会得到解决。
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT 23, ud.DBID, Yellow
FROM Inventory U INNER JOIN Users ud
ON U.PurchasedByUser = ud.DBID AND ud.UserActive = 1 AND ud.UserName = 'mathew'
答案 1 :(得分:1)
将U.DBID更改为ud.DBID
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT 23, ud.DBID, 'Yellow'
FROM Inventory U INNER JOIN Users ud
ON U.PurchasedByUser = ud.DBID AND ud.UserActive = 1 AND ud.UserName = 'mathew';
答案 2 :(得分:0)
在您构建的SQL查询中,您指的是U的DBID,它是Inventory表。从您分享的结构中,我认为您需要以下查询:
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT 23, ud.DBID, Yellow
FROM Inventory U INNER JOIN Users ud
ON U.PurchasedByUser= ud.DBID AND ud.UserActive = 1 AND UserName = 'mathew'
我仍然对在这里尝试实现的目标感到困惑,你从库存中获取值并再次插入它。不确定。只是试图帮助你弄清楚查询!
答案 3 :(得分:0)
您可以通过两个步骤完成此操作。首先获取用户的ID:
SELECT DBID
FROM Users
WHERE UserActive=1 AND UserName='mathew';
现在您拥有了用户的ID,您可以使用第二个查询将其插入Inventory
表:
INSERT INTO Inventory (ProductID,PurchasedByUser,OtherAttributes )
VALUES(23,<THE-USER'S-ID>, 'Yellow');
我假设您知道如何在PHP中执行此操作,因为您不需要PHP代码
答案 4 :(得分:0)
我相信23
&amp; Yellow
是记录您quote
需要mathew
。
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT 23, U.DBID, Yellow
FROM Inventory U INNER JOIN Users ud
ON U.DBID = ud.DBID AND ud.UserActive = 1 AND UserName = mathew
到此
INSERT INTO Inventory (ProductID, PurchasedByUser, OtherAttributes)
SELECT ProductID, PurchasedByUser , OtherAttributes
FROM Inventory U INNER JOIN Users ud
ON U.DBID = ud.DBID AND ud.UserActive = 1 AND UserName = 'mathew'