MySql Query - INSERT INTO command but only without duplicates
I have this workable query which is inserting proper data into 'selections' table according to some conditions:
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.BetfairMa开发者_如何学运维rk = game.BetfairMarketID), 2,
((SELECT id FROM auctions, game WHERE auctions.BetfairMark = game.BetfairMarketID), 3
but my problem is how to improve this query to prevent getting same duplicates in table when running this query?
Selections table have 3 columns: id, auctionid, order where id is autoincrement number generated for each new record.
So auctionid and order shouldn't be the same values in record.
Add a UNIQUE INDEX
to the (auctionid, order)
pair.
ALTER TABLE selections ADD UNIQUE index_name (`auctionid`, `order`)
And when you insert you can use INSERT IGNORE INTO ...
so that it ignores duplicates instead of throwing an error. (Useful when you batch insert and the duplicates are expected)
SOLVED! Created 3 separated queries for each row, working for now!
So with added UNIQUE INDEX to the (auctionid, order) pair have this workable code:
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
;
精彩评论