简体   繁体   English

MySQL查询获取联接表结果

[英]MySQL query to get joined table results

There is a chance this has been asked but I'm not entirely sure how to word it which makes searching for an answer a bit difficult. 有可能有人问过这个问题,但我不完全确定该如何措辞,这使得寻找答案有些困难。

I have a table of accommodation listings (listingid (primary key), listing_name, description, etc..). 我有一张住宿清单表(listingid(主键),listing_name,description等。)。 I then have another table for attributes relating to each listing (attributeid (primary key), listingid, attribute). 然后,我有了另一个与每个列表相关的属性的表(属性ID(主键),listingid,属性)。 Each attribute takes up its own row in the table - I realise this could be much smarter but have inherited the data structure. 每个属性都在表中占据其自己的行-我意识到这可能更聪明,但继承了数据结构。

My example of what I want to achieve is: 我想要实现的示例是:

SELECT all listings where attributes have "WiFi" AND "Air Conditioning" AND "Swimming Pool"

Along with these must have attributes, I only want to return listings that match ANY of the following: "Motel", "Hotel", "Apartment". 除了这些必须具有的属性外,我只想返回与以下任意一项匹配的列表:“汽车旅馆”,“酒店”,“公寓”。

I was initially doing a INNER JOIN on the attributes table and then going WHERE (attribute = "X" AND attribute = "Y") AND (attribute = "XX" OR attribute = "YY") but realised that the start of this statement will never match multiple rows as it is only ever checking against a single row. 我最初是在属性表上进行INNER JOIN,然后转到WHERE (attribute = "X" AND attribute = "Y") AND (attribute = "XX" OR attribute = "YY")但意识到该语句的开头永远不会匹配多行,因为它只针对单行进行检查。 So need to consider the entire result of the JOIN (or sub query?) which is where I need to expand my SQL understanding. 因此,需要考虑JOIN(或子查询?)的整个结果,这是我需要扩展SQL理解的地方。

I don't really want to go down my typical route of creating x amount of sub-queries as I imagine this will make the entire query extremely slow - especially if a user selected a dozen or more attributes to search on. 我真的不想沿用创建x数量的子查询的典型方法,因为我认为这会使整个查询非常慢-尤其是当用户选择了十几个或更多属性进行搜索时。

Hopefully this explains it enough but let me know if you require more information. 希望这足以说明问题,但是如果您需要更多信息,请告诉我。

Something like this should work: 这样的事情应该起作用:

select
    acc.*
from
    accomodation acc
    join attribute air on acc.id = air.accomodation_id and air.name='Air'
    join attribute pool on acc.id = pool.accomodation_id and pool.name='Pool'
    and acc.type in ('Motel', 'Hotel', 'Appartment')
;
select l.listingid, l.listing_name 
from listings l join attributes a 
on l.listingid = a.listingid
where a.attribute = 'WiFi' 
and a.attribute = 'Air Conditioning' and a.attribute = 'Swimming Pool'
and l.description in ('Motel', 'Hotel', 'Apartment')

The column names as per your conditions have been assumed. 假定根据您的条件使用列名。 But this should get you what you need. 但这应该可以为您提供所需的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM