iT邦幫忙

0

如何在同個資料表下,不同的WHERE篩選條件之下的兩個$SQL指令下做相減

  • 分享至 

  • xImage
$s1="SELECT a ,c  from sub where a='1'";
$s2="SELECT b ,c  from sub where b='1'";

要如何在PHP語言中取出$s1和$s2的'c' 並相減
或者是如何在一個指令下做出兩個指令相減

INSERT INTO sub
VALUES (1,2,55),(1,3,66),(1,4,77),(2,1,88),(2,3,99),(2,4,22),(3,1,33),(3,2,44),(3,4,55),(4,1,66),(4,2,77),(4,3,88);

https://ithelp.ithome.com.tw/upload/images/20220212/20146045FZkQj16oaf.png
我試過

SELECT ((SELECT c from sub where a='1')-(SELECT c from sub where b='1')) LIMIT 0, 25

MySQL 的回應是
#1242 - Subquery returns more than 1 row

相依性呢???誰減誰??
這沒辦法跑吧。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
kulu
iT邦新手 5 級 ‧ 2022-02-11 08:45:11
最佳解答

自己在修改運用..

SELECT (s1.c - s2.c) AS c,
    s1.a AS 's1-a',
    s1.b AS 's1-b',
    s2.a AS 's2-a',
    s2.b AS 's2-b'
FROM sub s1 , (
    SELECT * FROM sub WHERE b = 1 #查數值不要加引號
) s2
WHERE s1.a = 1; #查數值不要加引號
a22482351 iT邦新手 5 級 ‧ 2022-02-12 10:36:09 檢舉

我剛才發現我圖表有誤,但是感謝kulu的語法,讓我知道怎麼寫了

SELECT (s1.c - s2.c) AS D,
    s1.a AS 's1a',
    s1.b AS 's1b',
    s2.a AS 's2a',
    s2.b AS 's2b'
FROM sub s1 , ( SELECT * FROM sub WHERE b = 1 ) s2
WHERE s1.a = 1 and s1.b=s2.a;
0
ckp6250
iT邦好手 1 級 ‧ 2022-02-10 07:33:42

$s3=SELECT ((SELECT c from sub where a='1')-(SELECT c from sub where b='1'));

我要發表回答

立即登入回答