只是似乎无法让mysql查询正确

时间:2011-11-16 00:08:27

标签: mysql

我正在尝试获得我知道的结果,但似乎无法使查询正确。我使用以下内容:

SELECT 
    * 
FROM 
    carpets AS c 
    INNER JOIN carpet_relations AS r ON c.id = r.carpet_id 
WHERE 
    c.active = '1' 
    AND **((r.relation_type = '5') 
    AND (r.related_id = '1' ))** 
    *AND* ((r.relation_type = '4') 
    AND (r.related_id = '1')) 
    AND (c.width_feet BETWEEN '0' AND '17') 
    AND (c.width_inches BETWEEN '0' AND '11') 
    AND (c.height_feet BETWEEN '0' AND '29') 
    AND (c.height_inches BETWEEN '0' AND '11') 
ORDER BY 
    c.item_no

你可以看到我正在尝试得到的结果在第二个表中有两个匹配的字段,如果我改变了,并且斜体显示为或者我得到结果但是它是两个结果我需要结果在设置在之前,并且是粗体

所以它会是这样的:

具有关系类型5和4的列表

请记住,相关的ID可能有所不同,因为有三个colums carpet_id,related_id,relation_type

感谢您的帮助

c_categories 列类型为空默认注释 id int(11)否
title varchar(250)否
active int(11)否
weight int(11)没有
template_id int(11)否

c_sizes 列类型为空默认注释 id int(11)否
title varchar(250)否
active int(11)否
weight int(11)没有
template_id int(11)否

carpet_relations

列类型为空默认注释

carpet_id int(11)否< ------表示与之关系的地毯

related_id int(11)否< ------要使用的c_size或c_categories的id

relation_type int(11)否< ------表示c_sizes或c_categories

哪个表

4 个答案:

答案 0 :(得分:2)

改变这个:

((r.relation_type = '5') AND (r.related_id = '1' )) AND ((r.relation_type = '4') AND (r.related_id = '1'))

到此:

(r.relation_type = '5' OR r.relation_type = '4') AND (r.related_id = '1')

答案 1 :(得分:1)

为了灵活性:

r.relation_type IN (4, 5)

答案 2 :(得分:0)

AND ((r.relation_type = '5')
AND ((r.relation_type = '4') 

您期望关系类型同时为5和4。

你想要在你的沙拉中加入一些“或”吗?

编辑:

SELECT 
    * 
FROM 
    carpets AS c 
    INNER JOIN carpet_relations AS r ON c.id = r.carpet_id 
WHERE 
    c.active = '1' 
    AND 
((r.relation_type = '5') AND (r.related_id = '1' ))
    OR 
((r.relation_type = '4') AND (r.related_id = '1')) 

    AND (c.width_feet BETWEEN '0' AND '17') 
    AND (c.width_inches BETWEEN '0' AND '11') 
    AND (c.height_feet BETWEEN '0' AND '29') 
    AND (c.height_inches BETWEEN '0' AND '11') 
ORDER BY 
    c.item_no

解决您的问题。

答案 3 :(得分:0)

现在我认为我理解你的问题 - 你是在类型5和类型4的结果之后。

这可以通过做两个查询并将它们相交来在PHP中完成,或者你可以在MySQL中通过两次加入carpet_relations表来实现这一点:

SELECT 
    * 
FROM 
    carpets AS c 
    INNER JOIN carpet_relations AS r1 ON c.id = r1.carpet_id 
    INNER JOIN carpet_relations AS r2 ON c.id = r2.carpet_id
WHERE 
    c.active = '1' 
    AND (r1.relation_type = '5')
    AND (r1.related_id = '1' )
    AND (r2.relation_type = '4')
    AND (r2.related_id = '1')
    AND (c.width_feet BETWEEN '0' AND '17') 
    AND (c.width_inches BETWEEN '0' AND '11') 
    AND (c.height_feet BETWEEN '0' AND '29') 
    AND (c.height_inches BETWEEN '0' AND '11') 
ORDER BY 
    c.item_no