SQL中RIGHT JOIN的DISTINCT值

时间:2017-07-14 10:24:14

标签: php mysql sql

我有三个关系表,结构如下所示。

properties:

property_id | property_name | county_id 
------------|---------------|-------
     1      | Davis Court   |   2
     2      | Rose Lodge    |   1
     3      | Haven Court   |   4
     4      | Great Lodge   |   1
     5      | Lilly Court   |   2
     6      | Miles Lodge   |   4
     7      | Priory Court  |   5


testimonials:

testimonlal_id | property_id | message
---------------|-------------|------------------
      1        |    4        |   blah blah blah
      2        |    2        |   blah blah blah
      3        |    6        |   blah blah blah
      4        |    3        |   blah blah blah
      5        |    1        |   blah blah blah
      6        |    7        |   blah blah blah
      7        |    5        |   blah blah blah

counties:

county_id | county_name
----------|----------------
    1     | Berkshire
    2     | Devon
    3     | Essex
    4     | Kent
    5     | Surrey

我想为表格中的所有推荐显示不同的县名。我目前有以下查询。

SELECT DISTINCT properties.county_id, counties.county_id, 
counties.county_name, testimonials.testimonial_id 
FROM properties 
LEFT JOIN counties 
  ON properties.county_id = counties.county_id 
RIGHT JOIN testimonials 
  ON properties.property_id = testimonials.property_id 
ORDER BY properties.county_id ASC

目前这给了我

Berkshire
Berkshire
Devon
Devon
Kent
Kent
Surrey

但我想要

Berkshire
Devon
Kent
Surrey

这可能需要使用UNION或GROUP BY运算符,但我不确定如何调整查询。

提前致谢

3 个答案:

答案 0 :(得分:0)

目前还不清楚为什么要选择testimonials.testimonial_id为什么要为您的下拉框选择县。只需从选择列表中删除它就会导致县没有重复。

您可以通过不加入(因此不必解除带DISTINCT的行)来更清楚地了解这一点。当您要选择的县时,请从counties中选择。如果您有要选择的条件的标准,则将此条件放在WHERE子句中。

select county_name, county_id
from counties
where county_id in
(
  select county_id
  from properties
  where property_id in (select property_id from testimonials)
);

答案 1 :(得分:0)

如果您想要所有推荐书,请从该表开始并使用left join

SELECT c.county_id, c.county_name, t.testimonial_id 
FROM testimonials t LEFT JOIN
     properties p
     ON p.property_id = t.property_id LEFT JOIN
     counties c
     ON p.county_id = c.county_id 
ORDER BY p.county_id ASC;

注意:

    除非您在基础表中有重复项,否则
  • SELECT DISTINCT应该是不必要的。如果是这样,请将其重新放入。
  • 表别名使查询更易于编写和阅读。
  • 使用外连接时,我建议仅使用LEFT JOIN s。逻辑更容易理解:"将所有表保留在第一个表中,并使用其余表中的匹配列。
  • 无需选择county_id两次。

答案 2 :(得分:0)

http://sqlfiddle.com/#!6/4bcc2/11

SELECT TOP 1 WITH TIES 
p.county_id p_county_id, c.county_id c_county_id, c.county_name, t.testimonial_id, t.message
FROM properties p
LEFT JOIN counties c
  ON p.county_id = c.county_id 
RIGHT JOIN testimonials t
  ON p.property_id = t.property_id 
ORDER BY
    ROW_NUMBER() OVER(PARTITION BY  p.county_id ORDER BY [testimonial_id]);