其他一切的SQL

时间:2009-07-13 22:13:02

标签: mysql join

考虑两个数据库表ReportsReports_has_properties

Reports
------
id_report
1
2
3

Reports_has_properties
----------------------
id_report property
1         red
1         big
2         orange
3         blue
3         tiny

问题:例如,我只获取属性为红色的报告,但查询会返回与id_report匹配的所有id_report

SELECT * FROM reports
INNER JOIN reports_has_properties
    ON reports_has_properties.id_report = reports.id_report
WHERE reports_has_properties.property = 'red'

合乎逻辑的解释是: IF reports_has_properties有另一个属性的id_report,不要选择它! id_report 1属性为红色和大,所以不好。 但是如果我搜索属性orange,id_report 2只有一个属性,所以没关系。

我尝试了很多东西,但我没有更多的想法。非常感谢。

3 个答案:

答案 0 :(得分:2)

SELECT *
FROM reports
INNER JOIN reports_has_properties
    ON reports_has_properties.id_report = reports.id_report
WHERE reports_has_properties.property = 'red'

与:

相同
SELECT *
FROM reports
INNER JOIN reports_has_properties
    ON reports_has_properties.id_report = reports.id_report
    AND reports_has_properties.property = 'red'

不一样
SELECT *
FROM reports
LEFT JOIN reports_has_properties
    ON reports_has_properties.id_report = reports.id_report
    AND reports_has_properties.property = 'red'

我不确定你的目标是什么。

我认为你的目标可能是:

SELECT *
FROM reports
INNER JOIN reports_has_properties
    ON reports_has_properties.id_report = reports.id_report
WHERE reports.id_report IN (
    SELECT reports_has_properties.id_report
    FROM reports_has_properties
    WHERE reports_has_properties.property = 'red'
)

即。获取具有红色属性的任何报告的所有报告属性。

答案 1 :(得分:0)

很难说出你所追求的结果。

如果你想要所有的红色:

SELECT * FROM reports R
INNER JOIN reports_has_properties P
    ON P.id_report = R.id_report
WHERE P.property  = 'red';

如果你想要所有的3:

SELECT * FROM reports R
INNER JOIN reports_has_properties P
    ON P.id_report = R.id_report
WHERE P.id_report = 3;

答案 2 :(得分:0)

我不清楚你在找什么......

此查询将返回包含“red”属性的所有报告以及该report_id的所有其他属性。

SELECT R.*,P.property
  FROM reports R
     , reports_has_properties P
 WHERE R.id_report = P.id_report
   AND R.id_report in (select distinct id_report 
                         from reports_has_properties 
                        where property='red'
                      )