编辑:如果值不存在,则在连接语句中获取空值

时间:2015-11-18 09:27:14

标签: php mysql sql laravel

编辑:非常感谢您的所有帮助,但我可能没有关于NULL值的问题。实际上我希望它也考虑空值。因为没有办法对空值进行计算。 我希望它在价格列之前添加空值,如果它没有退出。 无论如何这样做?谢谢,再次抱歉。 不知道我可能遇到这个问题。

╔══════════╤════════════╤═══════════╤══════════════╗
║ store_id │ product_id │ now_price │ before_price ║
╠══════════╪════════════╪═══════════╪══════════════╣
║ 1        │ 2          │ 20000     │ NULL         ║
╟──────────┼────────────┼───────────┼──────────────╢
║ 2        │ 2          │ 18000     │ 21000        ║
╟──────────┼────────────┼───────────┼──────────────╢
║ 3        │ 2          │ 10000     │ NULL         ║
╚══════════╧════════════╧═══════════╧══════════════╝
  

我有两个价格表,其中一个是现在和其中一个   是为了以前。表结构是这样的:

     

现在:

╔══════════╤════════════╤═══════╗
║ store_id │ product_id │ price ║
╠══════════╪════════════╪═══════╣
║ 1        │ 2          │ 20000 ║
╟──────────┼────────────┼───────╢
║ 2        │ 2          │ 30000 ║
╟──────────┼────────────┼───────╢
║ 3        │ 2          │ 25000 ║
╚══════════╧════════════╧═══════╝
     

之前:

╔══════════╤════════════╤═══════╗
║ store_id │ product_id │ price ║
╠══════════╪════════════╪═══════╣
║ 1        │ 2          │ 19800 ║
╟──────────┼────────────┼───────╢
║ 2        │ 2          │ 28000 ║
╟──────────┼────────────┼───────╢
║ 3        │ 2          │ 24300 ║
╚══════════╧════════════╧═══════╝
     

现在我想要像表格中的数据区别   这个:

╔══════════╤════════════╤════════════╗
║ store_id │ product_id │ difference ║
╠══════════╪════════════╪════════════╣
║ 1        │ 2          │ -200       ║
╟──────────┼────────────┼────────────╢
║ 2        │ 2          │ -2000      ║
╟──────────┼────────────┼────────────╢
║ 3        │ 2          │ -700       ║
╚══════════╧════════════╧════════════╝
     

我该怎么做?谢谢。顺便说一句,也许有一个产品   在商店中不可用的可能是获得空值   它们?

5 个答案:

答案 0 :(得分:1)

内部联接非常方便。

SELECT T1.`store_id`,
       T2.`product_id`,
      (T1.`price`-T2.`price`) AS Difference
    FROM
    price_now T2
    INNER JOIN 
    price_before T1 ON T1.`store_id` = T2.`store_id` AND T1.`product_id` = T2.`product_id`

希望这有帮助。

答案 1 :(得分:0)

您可以使用SQL进行基本数学运算:

SELECT
    `a`.`store_id`,
    `a`.`product_id`,
    (`b`.`price` - `a`.`price`) AS `difference`
FROM `table1` AS `a`
LEFT JOIN `table2` AS `b` ON `a`.`store_id` = `b`.`store_id`

答案 2 :(得分:0)

您可以通过简单的连接

来完成此操作
select store_id, product_id, b.price -a.price from table1 a join table2 b on a.store_id=b.store_id and a.product_id=b.product_id

答案 3 :(得分:0)

尝试以下查询:

select
  case when exists (select product_id from table1 a 
  join table2 b on  a.product_id = b.product_id)
  then (select store_id, product_id, (b.price - a.price) as difference 
  from table1 a 
  join table2 b on a.store_id = b.store_id 
  and a.product_id = b.product_id) 
  else null
end

答案 4 :(得分:0)

试试这个......

SELECT now.store_id,now.product_id,now.price - before.price AS difference 
FROM now LEFT JOIN before ON now.store_id = before.store_id