0

Sorry if this is a basic question. I'm fairly new to SQL, so I guess I'm just missing the name of the concept to search for.

Quick overview.

First table (items):

ID     | name
-------------
1      | abc
2      | def
3      | ghi
4      | jkl

Second table (pairs):

ID     | FirstMember   | SecondMember         Virtual column (pair name)
-------------------------------------
1      | 2             | 3                    defghi
2      | 1             | 4                    abcjkl

I'm trying to build the virtual column shown in the second table It could be built at the time any entry is made in the second table, but if done that way, the data in that column would get wrong any time one of the items in the first table is renamed.

I also understand that I can build that column any time I need it (in either plain requests or stored procedures), but that would lead to code duplication, since the second table can be involved in multiple different requests.

So is there a way to define a "virtual" column, that could be accessed as a normal column, but whose content is built dynamically?

Thanks.

Edit: this is on MsSql 2008, but an engine-agnostic solution would be preferred.

Edit: the example above was oversimplified in multiple ways - the major one being that the virtual column content isn't a straight concatenation of both names, but something more complex, depending on the content of columns I didn't described. Still, you've provided multiple paths that seems promising - I'll be back. Thanks.

4

4 回答 4

4

您需要加入 items 表两次:

select p.id,
       p.firstMember,
       p.secondMember,
       i1.name||i2.name as pair_name
from pairs as p
  join items as i1 on p.FirstMember = i1.id
  join items as i2 on p.SecondMember = i2.id;

然后把它放到一个视图中,你就有了你的“虚拟列”。您只需pairs在需要列的地方查询视图而不是实际表pair_name

请注意,上面使用了内部联接,如果您的“FirstMember”和“SecondMember”列可能为空,您可能希望使用外部联接。

于 2013-07-30T13:54:14.243 回答
2

您可以使用视图,它从查询结果创建一个类似表的对象,例如提供了 a_horse_with_no_name 的对象。

CREATE VIEW pair_names AS
SELECT p.id,
    p.firstMember,
    p.secondMember,
    CONCAT(i1.name, i2.name) AS pair_name
FROM pairs AS p
    JOIN items AS i1 ON p.FirstMember = i1.id
    JOIN items AS i2 ON p.SecondMember = i2.id;

然后查询结果只需:

SELECT id, pair_name FROM pair_names;
于 2013-07-30T13:57:53.323 回答
0

如果您愿意,可以为您的“虚拟列”创建一个视图,如下所示:

CREATE VIEW aView AS

SELECT
    p.ID,
    p.FirstMember,
    p.SecondMember,
    a.name + b.name as 'PairName'
FROM
    pairs p
LEFT JOIN
    items a
ON
    p.FirstMember = a.ID
LEFT JOIN
    items b
ON
    p.SecondMember = b.ID

编辑:

或者,当然,您可以每次都使用类似的 select 语句。

于 2013-07-30T14:00:49.777 回答
0

从表中选择时,您可以使用 AS 命名列的结果。

SELECT st.ID, st.FirstMember, st.SecondMember, ft1.Name + ft2.Name AS PairName
FROM Second_Table st 
JOIN First_Table ft1 ON st.FirstMember = ft1.ID
JOIN First_Table ft2 ON st.SecondMember = ft2.ID

应该给你一些你所追求的东西。

于 2013-07-30T14:08:02.243 回答