使用JOIN和WHERE的SQL?

时间:2014-10-02 22:00:11

标签: sql

我一直试图解决这个问题,但过去几个小时都未能实现,但似乎无法弄明白。

我有两张表receiptsif_receipts_upl

receipts
-po
-receipt_type

if_receipts_upl
-po
-owner_id
-if_status
-if_date

现在我需要为除IBD之外的所有receipt_type写一个更新if_status以获取特定日期范围(if_date)的sql语句

这是我尝试过的,但是无法正常工作

SELECT  r.po,r.receipt_type, ifr.po FROM receipts AS r, if_receipts_upl AS ifr 
INNER JOIN if_receipts_upl
ON r.po=ifr.po AND ifr.owner_id='GIII'  
  AND (ifr.stat_date >='2014-07-01' AND ifr.stat_date   <'2014-08-01') 
ORDER BY ifr.stat_date

感谢您的帮助!

4 个答案:

答案 0 :(得分:0)

看起来这是因为你正在应用where条件的方式,虽然可以在join子句中执行其中某些操作,但它有时会导致一些你可能没想到的行为,我想这里正在发生。

尝试此查询:

SELECT  r.po,r.receipt_type, ifr.po FROM receipts AS r 
INNER JOIN if_receipts_upl AS ifr
ON r.po=ifr.po
WHERE ifr.owner_id='GIII'  
  AND (ifr.stat_date >='2014-07-01' AND ifr.stat_date   <'2014-08-01') 
ORDER BY ifr.stat_date

答案 1 :(得分:0)

试试这个......

SELECT r.po,
       r.receipt_type, 
       ifr.po 

FROM   receipts AS r 

       INNER JOIN if_receipts_upl ifr ON r.po=ifr.po 

WHERE  ifr.owner_id='GIII'  
       AND ifr.stat_date >= '2014-07-01' 
       AND ifr.stat_date <  '2014-08-01'

ORDER  BY ifr.stat_date

答案 2 :(得分:0)

如果您想更新(更改)if_status的值,您需要稍微不同的语法:

UPDATE if_receipts_upl                 -- table to update
SET if_status = 'new value'            -- column to change, and new value
FROM if_receipts_upl ifr               
INNER JOIN receipts r ON r.po=ifr.po 
WHERE ifr.owner_id='GIII'              -- where to filter what rows get changed
AND ifr.stat_date >= '2014-07-01' 
AND ifr.stat_date <  '2014-08-01'
AND r.receipt_type <> 'IBD'

答案 3 :(得分:0)

您指定要为“除IBD之外的所有receipt_type更新if_status的某个日期范围(if_date)”,但您提供的示例代码是 SELECT 语句,而不是< em> UPDATE 语句。 Select语句只返回值,它们不会更新数据库。要执行您的要求,您需要编写一个类似于您的select语句的UPDATE语句,其中包含您指定的条件。

UPDATE
    if_receipts_upl
SET
    if_status = -- YOUR UPDATED VALUE HERE
FROM
    if_receipts_upl AS i
    INNER JOIN
    receipts AS r
    ON
        i.po = r.po
WHERE
    i.owner_id = 'GIII'
    AND i.if_date BETWEEN '2014-07-01' AND '2014-08-01'
    AND receipt_type <> 'IBD' -- This fulfills one of the conditions you specify