我有一个有两个表的数据库,即:
船
with
table1(activity_timestamp, activity) as (
values
('2016-12-23 13:53:47.608561'::timestamp, 'details viewed'),
('2017-01-09 14:15:52.570397', 'details viewed'),
('2016-12-27 16:06:39.138994', 'details viewed'),
('2016-12-24 21:09:56.159436', 'details viewed')),
table2(activity_timestamp, activity) as (
values
('2016-12-23 13:54:47.608561'::timestamp, 'reading'),
('2017-01-09 14:17:52.570397', 'reading'),
('2016-12-27 16:10:39.138994', 'reading'),
('2016-12-24 21:012:56.159436', 'reading'))
select
*,
activity_timestamp - (select max(activity_timestamp) from table1 as t1 where t2.activity_timestamp > t1.activity_timestamp) as diff
from table2 as t2 order by activity_timestamp, activity;
记录
user_id|boat_id|sails
1 1 <sails><id135986><sailinfo>A2</sailinfo><sailtype>Main</sailtype></id135986><id185764><sailinfo>#3</sailinfo><sailtype>Jib</sailtype></id185764></sails>
1 2 <sails><id10230><sailinfo>A2</sailinfo><sailinfo>Main</sailinfo></id10230><id20000><sailinfo>#5</sailinfo><sailinfo>Genoa</sailinfo></id20000></sails>
2 3 <sails><id43567><sailinfo>A2</sailinfo><sailinfo>Main</sailinfo></id43567><id24503><sailinfo>#5</sailinfo><sailinfo>Genoa</sailinfo></id24503></sails>
这种结构背后的想法是,如果记录“sailinfo”和“sailtype”在表Boats中更新,则记录表不受影响,因为它通过id标记链接到另一个。
现在,我有一个应用程序,用户可以在其中选择sailinfo(例如A2),并且基于此输入,应生成查询以检索已使用该特定sailinfo的位置。结果应以表格格式显示,其中第一列(“位置”)包含相关位置,第二列应具有与“A2”相关联的“sailtype”作为标题,A2作为条目。例如,假设user_id = 2的用户为boat_id = 2输入“A2”,这是应该返回的内容:
user_id|boat_id|location |sails
1 1 San Francisco <sails><id135986>id135986</id135986><id185764>id185764</id185764></sails>
1 2 Chicago <sails><id10230>id10230</id10230></sails>
1 2 Chicago <sails><id20000>id20000</id20000></sails>
1 2 New York <sails><id10230>id10230</id10230><id20000>id20000</id20000></sails>
2 3 Bermuda <sails><id43567>id43567</id43567></sails>
我尝试使用以下SQL语句,但它不起作用:
location | Jib
Chicago A2
New York A2
当然,因为我从表Boats中选择,所以上面的“location”返回NULL,而“Jib”只返回一行:
我希望上面的描述足够清楚。
非常感谢您的帮助!
答案 0 :(得分:0)
该声明起初不起作用,因为在您的数据中,您没有'boat_id = 88'然后您没有'id28108'
以下代码返回您想要的内容:
SELECT
[location], Boats.sails.value('(/sails/id10230/sailinfo)[1]', 'nvarchar(50)') AS 'Jib'
FROM
#tbl_Boats as Boats
FULL JOIN
#tbl_Records as Records
ON Records.sails.value('local-name(/sails[1]/*[1])', 'nvarchar(50)')
= Boats.sails.value('local-name(/sails[1]/*[1])','nvarchar(50)')
WHERE Records.sails.value('(/sails/id10230)[1]', 'nvarchar(50)') is not null;
P.S。看上去不对劲。尝试在XML之外的列中存储一些值。这将更快地运行,并且更容易理解/排除故障。