Mysql查询过滤结果

时间:2015-07-15 06:05:52

标签: mysql database join

我有2张桌子

TBL 1: property               TBL 2: property_detail
---------------------         --------------------------------------
Id   Name   status            property_id   param       value
---------------------         --------------------------------------
1    X       1                  1          parking      two-wheeler 
2    Y       1                  1          furnishing   furnished  
3    Z       0                  2          parking      car-parking 
4    A       1                  2          furnishing   semi-furnished
5    B       1                  3          furnishing   furnished 
6    C       0                  4          parking      car-parking 
“property_detail”中的“property_id”列是“property”中“Id”列的外键

我希望搜索结果为status = 1和(param =“parking”和value =“car-parking”)和(param =“furnishing”和value =“furnished”)

从上面的示例表中,结果将是

Result
-------------
id   name
-------------
2     Y

如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

您可以使用详细信息表

连接两次来获得所需的结果集
select p.*
from property p
join property_detail d on (p.Id = d.property_id)
where p.status=1 
group by p.Id
having sum(param="parking" and value="car-parking") 
and sum(param="furnishing" and value="semi-furnished")

另一种方法也可以使用having子句和sum函数

来使用下面的查询
--create procedure in database A
create procedure dbo.StoredProc
(
@dbname --or dbid if you want
)
as
begin
   --create your sql command here, using dynamic sql maybe
   declare @sqlcmd NVARCHAR(MAX)=N''

   set @sqlcmd = 'SELECT * FROM ' + @dbname + '.dbo.AnyTable'
   exec sp_executesql @sqlcmd
end

--create a synonym for this procedure in database b:
create synonym dbo.StoredProc FOR databaseA.dbo.StoredProc

--then you can call your procedure in Database A and B like this:

declare @dbname NVARCHAR(100) = DB_NAME()

exec dbo.StoredProc @dbname

DEMO