开发者

Items in Multiple Categories Show Multiple Times

I've got items in an "equip" table that are linked to the equipcat table using a junction table. The problem is that I want to get a list of all items where the user supplied search term is found inside one of numerous fields, including the equipcat (aka category description) field. But I want each item to only be listed once.

It seems I must have some fundamental misunderstanding about SQL because I've faced this problem before and had trouble figuring it out. I'm not only looking to solve this particular issue but to also understand it better for future needs.

Here's my SQL. Please ignore the fuzzy searches as I realize they don't scale/perform well. I'm also aware that my use of a single field to hold keywords violates good design and I'm simply asking that you ignore that unless you feel that it is important to the question I'm asking.

SELECT equip.equipid, equip.equipdesc, e开发者_StackOverflow中文版quip.equipgeneraldesc, 
    equip.keywords, equip.dayprice, equip.weekprice, 
    equip.monthprice, equip.hideyn, equipcat.equipcat, 
    equipcat.equipcatkeywords 
FROM (equip INNER JOIN equip_equipcat ON equip.equipid = equip_equipcat.equipid)
INNER JOIN equipcat ON equip_equipcat.equipcatid = equipcat.equipcatid
WHERE (equip.equipdesc LIKE '%rake%' OR equip.keywords LIKE '%rake%' OR 
    equipcat.equipcat LIKE '%rake%' OR equipcat.equipcatkeywords LIKE '%rake%') 
    AND (equip.hideyn = 0)
ORDER BY equipdesc ASC;


SELECT  equip.*
FROM    equip e
WHERE   equipid IN
        (
        SELECT  equipid
        FROM    equip_equipcat ec
        JOIN    equipcat c
        ON      c.equipcatid = ee.equipcatid
        WHERE   equipcat LIKE '%rake%' 
                OR
                equipcatkeywords LIKE '%rake%'
        )
        AND
        (
        equipdesc LIKE '%rake%'
        OR
        keywords LIKE '%rake%'
        )
        AND hideyn  = 0
ORDER BY
        equipdesc 


A) You included fields From table equipcat into your result and thus a line is needed for each category anyways => remove those columns from your query

B) You may then add a distinct keyword to your query (i.e. SELECT DISTINCT...) and reduce multiple lines to distinct ones only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜