SQl 根据加入的 table 的某些 属性 值排序

SQl sorting based on certain property value of joined table

我有以下 tables 和一些数据:

Collector:
dcid  name   hostid userid
123   test   host1  234
567   hello  host2  345

CollectorConfiguration:
ID   propertyname  propertyvalue  collector_id(foreign key)
id1  c_source      local          123
id2  c_createdby   admin          123
id3  c_pattern     JBoss          123
id4  c_source      remote         567
id4  c_createdby   admin          567
id4  c_pattern     Apache         567

现在我需要从 Collector table 获取所有记录,并根据 CollectorConfiguration table 中的列值 "c_pattern" 进行排序。

我尝试使用内部联接编写查询,但无法获得所需的结果。请帮忙。

注意:返回的结果只包含 Collector table 的列,即它应该表现得像 select * 来自 Collector 但在 c_pattern 属性 上有 sortinn值。

Desired output(with ascending order on c_pattern):
567  hello host2 345
123  test  host1 234
SELECT a.* FROM Collector a
LEFT JOIN CollectorConfiguration b ON b.collector_id=a.dcid
WHERE b.propertyname="c_pattern"

这个问题对我来说不是很清楚,但我猜你正在寻找这个问题。

有了 EAV 模型,你应该有一堆帮助视图来克服这样的问题。视图将充当表,例如 collector_patterns、collector_sources 等

SELECT c.*
FROM Collector c LEFT JOIN
CollectorConfiguration cc on c.dcid = cc.collector_id
where cc.propertyname = 'c_pattern'
ORDER BY cc.propertyvalue DESC

因此,要从该查询中获取视图,您可以这样写:

CREATE VIEW collector_pattern AS
SELECT c.*, cc.propertyvalue AS pattern
FROM Collector c LEFT JOIN
CollectorConfiguration cc on c.dcid = cc.collector_id
where cc.propertyname = 'c_pattern'

模式还不清楚,但应该是这样的

SQL FIDDLE DEMO

SELECT c.[dcid], c.[name], [hostid], [userid]
FROM Collector c
LEFT JOIN CollectorConfiguration cc 
    ON cc.collector_id=c.dcid
WHERE cc.propertyname = 'c_pattern'