使用以下结构,如何在这个1:n关系中选择尊重多个条件的request
子集?
# Table 1: Request
uid
name
# Table 2: Additional Information
uid
type
value
request
表2的注释:type
可以是任何内容,即' product_name'或者'评级'。
如果我只想按给定的product_name
选择请求,我可以这样做:
SELECT * FROM request as r
LEFT JOIN additional_information as i
ON r.uid = i.request
WHERE i.type = 'product' AND i.value = 'Product Name'
如果我想按给定product_name
和rating
选择请求,我会坚持我的陈述必须是什么样的。我试图简单地添加另一个连接,但这给了我与给定product_name
相关的所有请求以及与给定评级相关的所有请求。我需要声明尊重这两个条件。
如上所述,这对我不起作用。
SELECT * FROM request as r
LEFT JOIN additional_information as i
ON r.uid = i.request
LEFT JOIN additional_information as a
ON r.uid = a.request
WHERE i.type = 'product' AND i.value = 'Product Name'
OR a.type = 'rating' AND a.value = 1
感谢帮助!
答案 0 :(得分:1)
将这些条件从WHERE
移至JOIN ON
条件,如
SELECT * FROM request as r
LEFT JOIN additional_information as i
ON r.uid = i.request
AND i.type = 'product' AND i.value = 'Product Name'
LEFT JOIN additional_information as a
ON r.uid = a.request
AND a.type = 'rating' AND a.value = 1;
并且绝对是,考虑到Strwabery的有价值的评论(错过了),而不是做select *
或select r.*
,你可能真的想要指定你想要获取的列名,这比*
性能明智,因为您没有使用投影获取不必要的数据;除非你真的想要取得一切。
答案 1 :(得分:0)
它可能会慢于其他产品,因为它会加入您的附加数据TWICE,一次是产品,再次是评级。这可能应该更改为单个左连接,否则你可能会得到笛卡尔结果膨胀你的答案。
SELECT *
FROM
request as r
LEFT JOIN additional_information as i
ON r.uid = i.request
AND ( ( i.type = 'product' AND i.value = 'Product Name' )
OR ( i.type = 'rating' AND i.value = 1 );