在WHERE子句中查询XML属性值

时间:2014-06-02 01:44:32

标签: mysql sql xml where

我在XML列中有以下xml数据

<LoyaltyInfo ServerDate="2056-12-12">
  <Accounts>
    <Acc ID="1" Value="2.750" UpToDate="2014-05-13 18:38:00" />
    <Acc ID="2" Value="2.750" UpToDate="2014-05-13 18:38:00" />
    <Acc ID="3" Value="141.06" UpToDate="2014-05-22 12:53:00" />
    <Acc ID="6" Value="924.42" UpToDate="2014-06-01 16:53:00" />
    <Acc ID="7" Value="2895" UpToDate="2014-05-13 18:38:00" />
 </Accounts>
</LoyaltyInfo>

我想编写一个SQL查询来说明WHERE Acc ID = x并且在同一行中Acc Value = y

我尝试过以下但是我收到了错误

    SELECT *
    FROM TableName
    WHERE xmlData.exist('/LoyaltyInfo/Accounts/Acc[@ID="20"]') = 1 
    AND xmlData.value('/LoyaltyInfo/Accounts/Acc/@Value','integer') = 0

SELECT *
FROM TableName
WHERE xmlData.exist('/LoyaltyInfo/Accounts/Acc[@ID="20"]') = 1 
AND   xmlData.value('/LoyaltyInfo/Accounts/Acc[@Value]','integer') = 0

2 个答案:

答案 0 :(得分:1)

使用fn.min()函数尝试此查询以模拟AND运算符:

select *
FROM T
WHERE xmldata.value('fn:min((LoyaltyInfo/Accounts/Acc/@ID="3",
              LoyaltyInfo/Accounts/Acc/@Value="141.06"))','bit')=CAST(1 as bit) 

SQLFiddle demo

答案 1 :(得分:0)

对于未来的任何其他人来说,仅供参考

对于1个条件

select xmldata.query('for $loyaltyinfo in /LoyaltyInfo/Accounts                          
let $id :=$loyaltyinfo/Acc/@ID
let $value := $loyaltyinfo/Acc/@Value
where $id = "19" and $value = "141.06"
return $loyaltyinfo
') as [Valid Data]
FROM T

2个条件

select xmldata.query('for $loyaltyinfo in /LoyaltyInfo/Accounts                          
let $id :=$loyaltyinfo/Acc/@ID
let $value := $loyaltyinfo/Acc/@Value
where ($id = "19" and $value = "141.06") and ($id = "20" and $value = "0.00")
return $loyaltyinfo
') as [Valid Data]
FROM T