我有一个名为'computers'的表,其中包含以下cols:
ROW_ID
COMPUTER_ID
关键
值
键等于'3'的行的值包含计算机的名称
key等于'4'的行的值包含计算机的IP
键等于'5'的行的值包含计算机的用户
Computer_id代表一个特定的唯一计算机
我想创建一个具有以下列的视图:
COMPUTER_ID
命名
IP_ADDRESS
用户
我正在努力解决这个问题。我确信它不会那么复杂,但很难尝试多次引用相同的列(键,值)
提前谢谢。
答案 0 :(得分:3)
您可以按计算机ID进行分组,然后使用max和case选择正确的键。例如:
select computer_id
, max(case when key = 3 then value end) as Name
, max(case when key = 4 then value end) as IP
, max(case when key = 5 then value end) as User
from YourTable
group by
computer_id
答案 1 :(得分:1)
CREATE VIEW your_view
AS
SELECT x.computer_id, x.value AS name, y.value AS ip_address, z.value AS user
FROM computers AS x
INNER JOIN computers AS y
ON x.computer_id = y.computer_id
INNER JOIN computers AS z
ON x.computer_id = z.computer_id
WHERE x.key = 3
AND y.key = 4
AND z.key = 5
答案 2 :(得分:0)
另一个解决方案是子查询:
SELECT
computer_id,
value AS 'name',
(SELECT value FROM computers sqi WHERE sqi.computer_id = computers.computer_id AND sqi.key = 4) AS 'ip',
(SELECT value FROM computers squ WHERE squ.computer_id = computers.computer_id AND squ.key = 5) AS 'user'
FROM
computers
WHERE
key = 3
答案 3 :(得分:0)
select computer_id,
max(case when [KEY] = 3 then value end) as Name,
max(case when [KEY] = 4 then value end) as IP,
max(case when [KEY] = 5 then value end) as [User]
from YourTable
group by computer_id
答案 4 :(得分:0)
您要查询的是遵循EAV model设计的表格。以下是article with some examples如何/需要查询EAV。
以下是表定义的子查询示例:
SELECT x.Computer_Id,
(SELECT value FROM Computers AS a WHERE x.Computer_Id = a.Computer_Id AND [key]= 3) AS 'Name',
(SELECT value FROM Computers AS b WHERE x.Computer_Id = b.Computer_Id AND [key]= 4) AS 'IpAddress',
(SELECT value FROM Computers AS c WHERE x.Computer_Id = c.Computer_Id AND [key]= 5) AS 'User'
FROM Computers as x
GROUP BY x.Computer_Id