我有这个可行的查询,它根据一些条件将适当的数据插入'selections'表:
INSERT INTO selections (auctionid, selections.order)
VALUES
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 1,
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 2,
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 3
但我的问题是如何改进此查询以防止在运行此查询时在表中获得相同的重复项?
选择表有3列:id,auctionid,order其中id是为每个新记录生成的自动增量号。
因此,拍卖和订单的记录价值不应相同。
答案 0 :(得分:1)
将UNIQUE INDEX
添加到(auctionid, order)
对。
ALTER TABLE selections ADD UNIQUE index_name (`auctionid`, `order`)
当您插入时,您可以使用INSERT IGNORE INTO ...
,以便它忽略重复项而不是抛出错误。 (批量插入时很有用,并且需要重复)
答案 1 :(得分:0)
解决了! 为每一行创建了3个单独的查询,现在正在使用!
因此,通过为(auctionid,order)对添加UNIQUE INDEX,可以使用以下代码:
INSERT IGNORE INTO
selections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
1,
PlayerA,
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;
INSERT IGNORE INTO
elections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
2,
PlayerB,
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;
INSERT IGNORE INTO
selections
(
selections.auctionid,
selections.order,
selections.title,
startamount
)
SELECT
auctions.id,
3,
'third text',
0.01
FROM
auctions, game
WHERE
auctions.BetfairMark = game.BetfairMarketID
;