我需要帮助设计一个SQL表。假设我有 cardnumber , cardtype ,field1,field2和field3。
Cardtype 是一个枚举,可以是“前”,“后”或“两者”。
我想选择front.field1,front.field2,front.field3,back.field1,back.field2,back.field3 FROM某些表或视图WHERE cardnumber = XXX。
大多数记录只包含field1,field2,field3和“both”,表示我应该将front.field1与back.field1等相同...当我选择时。当“前”和“后”不同时,我将需要两行具有相同的卡号,但一行具有“前”而另一行带有“后”,以及每一侧的相应field1 ... field3。
如何设计此表。我应该使用某种INNER JOIN的视图还是某种左/右连接?
我对不同的设计持开放态度,但我希望任何设计都易于维护(考虑到大多数记录将是包含“both”的一行)并且可以满足我的SELECT要求。
答案 0 :(得分:1)
Card
--------------------------------------------
CardNumber CardType_id field1 etc
CardType
--------------------------------------------
ID Description
SELECT
Card.*,
CardType.Description
FROM Card
INNER JOIN CardType
ON Card.CardType_id = CardType.ID
WHERE CardType.Description = 'your description value'
答案 1 :(得分:1)
似乎您已经考虑了设计并且正在寻找查询。我添加了create table / insert语句来显示我对该问题的解释。这假定了许多完整性项目,例如:
如果你有一张卡片的'FRONT'记录,你也会有一张(和。) 只有一张卡片的'BACK'记录。我
如果您有一张卡的'BOTH'记录,则不会有其他记录
使用Postgresql:
CREATE TABLE card(cardnumber int, cardtype varchar(5), field1 varchar(16), field2 varchar(16), field3 varchar(16));
INSERT INTO card VALUES(1, 'FRONT', 'a', 'b', 'c');
INSERT INTO card VALUES(1, 'BACK', 'd', 'e', 'f');
INSERT INTO card VALUES(2, 'BOTH', 'x', 'y', 'z');
SELECT c1.cardnumber
,c1.field1 AS frontField1, c1.field2 AS frontField2, c1.field3 AS frontField3
,c2.field1 AS backField1, c2.field2 AS backField2, c2.field3 AS backField3
FROM card c1
,card c2
WHERE c1.cardtype = 'FRONT'
AND c2.cardtype = 'BACK'
AND c1.cardnumber = c2.cardnumber
UNION
SELECT c.cardnumber
,c.field1 AS frontField1, c.field2 AS frontField2, c.field3 AS frontField3
,c.field1 AS backField1, c.field2 AS backField2, c.field3 AS backField3
FROM card c
WHERE c.cardtype = 'BOTH';
cardnumber | frontfield1 | frontfield2 | frontfield3 | backfield1 | backfield2 | backfield3
------------+-------------+-------------+-------------+------------+------------+------------
1 | a | b | c | d | e | f
2 | x | y | z | x | y | z