简体   繁体   English

具有多个表的联结表上的MySQL SELECT查询

[英]MySQL SELECT query on junction table with multiple tables

I have four tables, assuming they have only an id as a column each. 我有四个表,假设每个表只有一个ID作为列。

  • listings
  • feature
  • location
  • l_f_location as a junction table with FKs on listingId , featureId , locationId l_f_location作为带有FK的联结表,在listingIdfeatureIdlocationId

I try to query the l_f_location table for a given set of locationIds (logical AND match) and want as a result only those listings which match ALL the locationIds , eg (7 AND 9 AND 10). 我尝试在l_f_location表中查询给定的locationIds集(逻辑AND匹配),结果只希望那些与所有locationIds匹配的列表,例如(7 AND 9 AND 10)。

l_f_location looks like l_f_location看起来像

listingId featureId locationId
10        5         7
10        7         7
10        8         9
11        4         7
11        8         9
11        9         10
11        12        14

The goal is to retrieve only listingId 11 in this case - matching the set of locationIds 7, 9 and 10. 在这种情况下,目标是仅检索listingId 11-与locationIds 7、9和10的集合匹配。

I tried the following query 我尝试了以下查询

" SELECT id, COUNT(*) as num FROM l_f_locations WHERE locationId IN ( 7, 9, 10) GROUP by listingId, locationId HAVING num = 3 " SELECT id, COUNT(*) as num FROM l_f_locations WHERE locationId IN ( 7, 9, 10) GROUP by listingId, locationId HAVING num = 3

But that gives wrong values of count as the grouping kicks in. 但是,随着分组的开始,计数值会错误。

A similar query works perfectly on a simpler junction table eg only l_location with eg " SELECT id, COUNT(*) as num FROM l_location WHERE locationId IN ( 7, 9, 10) GROUP by listingId HAVING num = 3 ". 类似的查询可以在更简单的联结表上完美地工作,例如仅l_location,例如“ SELECT id, COUNT(*) as num FROM l_location WHERE locationId IN ( 7, 9, 10) GROUP by listingId HAVING num = 3 ”。

Rgds, P. Rgds,P。

I'm assuming that the same listingId and locationId can have multiple featureId s? 我假设相同的listingIdlocationId可以具有多个featureId Otherwise it's quite a bit easier. 否则,它会容易得多。

If that is the case: 如果是这样的话:

SELECT listingId, COUNT(*) as num 
FROM
(SELECT DISTINCT listingId, locationId
 FROM l_f_locations
 WHERE locationId IN ( 7, 9, 10)) AS sub
GROUP by listingId, HAVING num = 3 

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

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