![](/img/trans.png)
[英]Search for an entry - in a Database ( without specifying a Column name/Table name)
[英]How to search an entry in a table and return the column name or index in PostgreSQL
我有一张代表卡片组的桌子,其中有 4 张卡片,每张卡片都有一个唯一的 ID。 现在我想在表中查找特定的卡片 ID,并找出它是牌组中的哪张卡片。
卡1 | 卡片 2 | 卡3 | 卡4 |
---|---|---|---|
卡ID1 | 卡ID2 | 卡ID3 | 卡ID4 |
例如,如果我的表喜欢这个,我想做类似的事情:SELECT column_name WHERE cardID3 IN (card1, card2, card3, card4)
寻找答案我发现了这个: SQL 服务器:根据记录的值返回列名
但这似乎不适用于 PostgreSQl
SQL 服务器的cross apply
是 SQL 标准cross join lateral
。
SELECT Cname
FROM decks
CROSS join lateral (VALUES('card1',card1),
('card2',card2),
('card3',card3),
('card4',card4)) ca (cname, data)
WHERE data = 3
示范。
然而,真正的问题是你的表的设计。 通常,如果您有 col1、col2、col3...,您应该改用连接表。
create table cards (
id serial primary key,
value text
);
create table decks (
id serial primary key
);
create table deck_cards (
deck_id integer not null references decks,
card_id integer not null references cards,
position integer not null check(position > 0),
-- Can't have the same card in a deck twice.
unique(deck_id, card_id),
-- Can't have two cards in the same position twice.
unique(deck_id, position)
);
insert into cards(id, value) values (1, 'KH'), (2, 'AH'), (3, '9H'), (4, 'QH');
insert into decks values (1), (2);
insert into deck_cards(deck_id, card_id, position) values
(1, 1, 1), (1, 3, 2),
(2, 1, 1), (2, 4, 2), (2, 2, 3);
我们确保一副牌不能有相同的牌,也不能有两张牌在同一个 position 中。
-- Can't insert the same card.
insert into deck_cards(deck_id, card_id, position) values (1, 1, 3);
-- Can't insert the same position
insert into deck_cards(deck_id, card_id, position) values (2, 3, 3);
可以直接查询卡的position。
select deck_id, position from deck_cards where card_id = 3
并且一副牌中的卡牌数量没有任意限制,您可以使用触发器申请一张。
示范。
这是一个相当糟糕的主意。 列名属于数据库结构,不属于数据。 因此,您可以将 select ID 和名称存储为数据,但不必将 select 列名称存储起来。 实际上,使用您的应用程序的用户不应该对列名称感兴趣; 他们可能相当技术性。
更改数据 model 并存储卡名称以及 ID 可能是个好主意,但我当然不知道您希望如何处理您的数据。
无论如何,如果你想坚持你当前的数据库设计,你仍然可以 select 这些名字,通过将它们包含在你的查询中:
select
case when card1 = 123 then 'card1'
when card2 = 123 then 'card2'
when card3 = 123 then 'card3'
when card4 = 123 then 'card4'
end as card_column
from cardtable
where 123 in (card1, card2, card3, card4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.