简体   繁体   中英

Deleting query in a SQL query without using types

I have created two tables, one has primitive types:

CREATE TABLE CARDS_BAD (
suit CHAR(1),
rank VARCHAR(2)
);

and the other one has a user defined types

CREATE TYPE suits AS ENUM ('♣', '♠', '♥', '♦');     
CREATE TYPE ranks AS ENUM ('2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', '10', 'A');

CREATE TABLE CARDS_GOOD (
suit suits,
rank ranks
);

as you can see, the two tables would contain cards decks of poker, cards are added using a simple INSERT query. When I try to delete all the cards with rank 7 or lower from the two tables:

DELETE FROM cards_bad t where t.rank < '7';
DELETE FROM cards_good t where t.rank < '7';

the query works correctly on cards_good but also deletes cards with rank 10 in cards_bad , but i expected the result to be the same. Can someone explain to me why it's different? Also let's say I want to INSERT a JOKER card into decks (which has a rank Jo but no suit), why doesn't this work?

There is a sensible difference between the tables: cards_good relies on an enum type to store the rank s, while cards_bads uses varchar() .

When doing string comparison, '10' < '7' , because '10' starts with '1' , which is smaller than '7' .

On the other hand, while comparing enum s seems to work in your use case, I don't that it is guaranteed to work consistently.

A probably safer option would be to create a lookup table that explicitly assigns a (numeric) weight to each rank .


On the joker card, that has a rank, but no suit : as far as concerns, suit is not a mandatory column in your table, so nothing should prevent you from inserting that card with a suit set to null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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