我有以下表格:
address_components(table)
ADDRESS_ID STREET_NUMBER STREET_NAME
-----------------------------------------------------
001 1402 Motz
002 505 31st
003 4100 Stimmel
属性(表格)
ID ATTRIBUTE_DEFINITION_ID VALUE
----------------------------------------------------------------
001 Lot 546
001 SubDiv Avondale Spring
002 Lot 546
002 SubDiv Garden
003 Lot 131
003 SubDiv Avondale Spring
以下SQL语句:
SELECT
street_number,street_name
FROM
address_components a, attributes attr
WHERE
a.address_id = attr.id
AND EXISTS (SELECT 1 FROM attributes
WHERE attr.attribute_definition_id = 'Lot'
AND attr.value = '546')
AND EXISTS (SELECT 1 FROM attributes
WHERE attr.attribute_definition_id = 'SubDiv'
AND attr.value = 'Avondale spring')
我正在尝试选择address_components row" 001"因为我正在尝试检索两个属性条目都为" lot = 546"和SubDiv = Avondale Spring"。不是两者都必须存在。
查询返回没有匹配项;但是,当我使用单个子查询进行查询时(消除2个子查询中的1个),将为该单个查询返回请求的行。
答案 0 :(得分:1)
查询背后的想法很好。但是from
子句中不需要两个表;你想要相关子查询:
SELECT a.street_number, a.street_name
FROM address_components a
WHERE EXISTS (SELECT 1
FROM attributes attr
WHERE a.address_id = attr.id AND attr.attribute_definition_id = 'Lot' AND attr.value = '546'
) AND
EXISTS (SELECT 1
FROM attributes attr
WHERE a.address_id = attr.id AND attr.attribute_definition_id = 'SubDiv' AND attr.value = 'Avondale spring'
);
答案 1 :(得分:0)
SELECT top 1 a.street_number,a.street_name from address_components a
inner join attributes k on a.ADDRESS_ID=k.ID
WHERE k.ATTRIBUTE_DEFINITION_ID in('Lot','SubDiv') AND
k.value in('546','Avondale Spring')