获取2个表中的记录数 - 一对多关系

时间:2014-02-19 09:34:25

标签: mysql sql join view

我遇到了搜索查询的问题,我必须动态构建才能从数据库中返回记录。

我有两张桌子:adds and adds_filters`。为了简单起见,我使表格增加了比它更短,删除了一些(不相关的)字段
我的表结构:

CREATE TABLE IF NOT EXISTS `adds` (
`addid` int(11) NOT NULL AUTO_INCREMENT,
`memberid` int(11) NOT NULL,
`isnew` int(11) NOT NULL,
`catid` int(11) NOT NULL,
`manufacturerid` int(11) NOT NULL,
`modelid` varchar(255) DEFAULT NULL,
`colorid` int(11) DEFAULT NULL,
`geographicareaid` int(45) NOT NULL,
`addtypeid` varchar(45) NOT NULL,
`addcreatedon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`addvalidfrom` date NOT NULL,
`addvaliduntil` date NOT NULL,
`addcreatedfromip` varchar(255) NOT NULL,
`yearofmanufacturing` varchar(255) DEFAULT NULL,
`monthofmanufacturing` int(11) DEFAULT NULL,
`hoursused` int(11) DEFAULT NULL,
`cc2` int(11) DEFAULT NULL,
`horsepowers` int(11) DEFAULT NULL,
`metalic` tinyint(4) DEFAULT NULL,
`isdamaged` tinyint(4) DEFAULT NULL,
`price` float DEFAULT NULL,
`hasvat` tinyint(4) NOT NULL,
`canbenegotiated` tinyint(4) DEFAULT NULL,
`addtitle` varchar(255) DEFAULT NULL,
`addtext` text NOT NULL,
`youtubevideo` varchar(255) DEFAULT NULL,
`visible` tinyint(4) DEFAULT NULL,
`ff1` varchar(255) DEFAULT NULL,
`ff2` varchar(255) DEFAULT NULL,
`ff3` varchar(255) DEFAULT NULL,
`ff4` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`addid`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=43 ;


CREATE TABLE IF NOT EXISTS `adds_filters` (
`addfilterid` int(11) NOT NULL AUTO_INCREMENT,
`addid` int(11) NOT NULL,
`filterid` int(11) NOT NULL,
 PRIMARY KEY (`addfilterid`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=45 ;

Here is the fiddle

问题是用户可以为每个添加添加多个过滤器,即如果是 车辆有AC,GPS,可移动舱等......这些数据存储在adds_filters中。因此,一个添加可以有很多过滤器。

当用户选择catid为1,manufacturerid为1,然后用户选中带有ID的过滤器时,查询应如何显示 例如67和158?

我更喜欢查看查询,但我不知道如何构建这样的视图。偏好视图的原因是在这种情况下,我将能够使用select *而不是复杂的查询......

任何帮助都将深受赞赏。

1 个答案:

答案 0 :(得分:1)

如果要显示filterid,使用此表结构,您需要为每个选中的filterid子查询。 如果不显示,您只需使用DISTINCTIN

Here is the query without displaying filterids

SELECT DISTINCT a.*
          FROM adds a
               JOIN adds_filters f
                    ON a.`addid` = f.`addid`
         WHERE      a.`catid` = 1
               AND  a.`manufacturerid` = 1
               AND  f.`filterid` IN (67, 158);

Here is the query, that displays two different filterids

SELECT t1.*, t2.filterid as filterid2
FROM
(
SELECT DISTINCT a.*,
       f.`filterid`
          FROM adds a
               JOIN adds_filters f
                    ON a.`addid` = f.`addid`
         WHERE      a.`catid` = 1
               AND  a.`manufacturerid` = 1
               AND  f.`filterid` = 67
) t1

JOIN 

(
SELECT DISTINCT a.`addid`,
       f.`filterid`
          FROM adds a
               JOIN adds_filters f
                    ON a.`addid` = f.`addid`
         WHERE      a.`catid` = 1
               AND  a.`manufacturerid` = 1
               AND  f.`filterid` = 158

  ) t2
ON t1.addid = t2.addid;