【问题标题】:SQL result not become as expect when using inner join使用内部联接时 SQL 结果未达到预期
【发布时间】:2017-01-13 09:24:29
【问题描述】:

我有一个无法回答的带有“内部联接”的 sql 查询。结果并没有如我所愿。甚至,我删除了“内连接”——结果也包括了所有内容——就像“内连接”一样。

如果我只希望结果来自这些条件怎么办?

  1. prop_type='5'
  2. 不是 prop_price='0'
  3. prop_price2='0'
  4. prop_price3='0'

Mysql:

select prop_lang, prop_type, prop_for, 
ppix_cover,prop_price,prop_price2,prop_price3 
from prop_db 
inner join prop_pix on prop_db.prop_sid=prop_pix.prop_sid 
where prop_db.prop_type='5' 
and prop_db.prop_lang='1' 
and prop_pix.ppix_cover='1' 
and prop_db.prop_for='1' or prop_db.prop_for='0' 
and prop_price3='0' 
and prop_price2='0' 
and not prop_price='0' 
group by prop_db.prop_sid 
order by prop_db.prop_id 
LIMIT 0, 9

这是上面查询的结果。

如您所见,“prop_type”列提供了我没想到的其他值。第一行还有 price2price3 不是 ='0'。

我应该怎么做才能使结果显示为上述条件?

【问题讨论】:

  • 你的 OR 语句是罪魁祸首。我没有您的表格的样本,但 OR 语句读作 (where this) OR (where this)。因此,查询将包括符合这两个条件的所有内容。使用括号使逻辑清晰并防止这种情况发生。

标签: mysql sql-server join


【解决方案1】:

一个疯狂的猜测,但它通常出现在:andor 需要括号。

半途而废:

select prop_lang, prop_type, prop_for, 
ppix_cover,prop_price,prop_price2,prop_price3 
from prop_db 
inner join prop_pix on prop_db.prop_sid=prop_pix.prop_sid 
where prop_db.prop_type='5' 
and prop_db.prop_lang='1' 
and prop_pix.ppix_cover='1' 
and (prop_db.prop_for='1' or prop_db.prop_for='0') 
and prop_price3='0' 
and prop_price2='0' 
and not prop_price='0' 
group by prop_db.prop_sid 
order by prop_db.prop_id 
LIMIT 0, 9

【讨论】:

    【解决方案2】:

    只需将“或”语句放在括号内

    prop_db.prop_for='1' or prop_db.prop_for='0' 
    

    试试这个,修改

       select prop_lang, prop_type, prop_for, 
       ppix_cover,prop_price,prop_price2,prop_price3 
        from prop_db 
        inner join prop_pix on prop_db.prop_sid=prop_pix.prop_sid 
        where prop_db.prop_type='5' 
        and prop_db.prop_lang='1' 
        and prop_pix.ppix_cover='1' 
        and (prop_db.prop_for='1' or prop_db.prop_for='0' )
        and prop_price3='0' 
        and prop_price2='0' 
        and not prop_price='0' 
        group by prop_db.prop_sid 
        order by prop_db.prop_id 
        LIMIT 0, 9
    

    【讨论】:

      【解决方案3】:

      也试试这个:

      SELECT prop_lang, 
          prop_type, 
          prop_for, 
          ppix_cover,
          prop_price,
          prop_price2,
          prop_price3 
      FROM prop_db 
      INNER JOIN prop_pix ON prop_db.prop_sid = prop_pix.prop_sid 
      WHERE prop_db.prop_type='5' 
          AND prop_db.prop_lang='1' 
          AND prop_pix.ppix_cover='1' 
          AND prop_db.prop_for IN ('1','0') 
          AND prop_price3='0' 
          AND prop_price2='0' 
          AND prop_price <> '0' 
      GROUP BY prop_db.prop_sid 
      ORDER BY prop_db.prop_id 
      LIMIT 0, 9
      

      【讨论】:

        猜你喜欢
        • 2017-09-07
        • 2017-01-21
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多