iT邦幫忙

0

這樣的情境該怎麼下SQL語法???

我有兩張不同的資料表,叫 prd1 和 prd2 好了。

prd1 的 id 和 prd2 的 pid 同樣都是產品的 id,現在我想知道這兩張資料表中,總計有多少不重複的產品 id,請問這樣的 sql 應該要怎麼下才會列出來?

另外,如果有第三個 prd3, 產品id的欄位名稱一樣是 id,現在我如果想要查 prd3 中,有哪些產品沒有出現在 prd1 和 prd2 中,又該怎麼查詢呢?

使用的資料庫是mysql,再請各位邦友前輩指導,謝謝。

hisniper iT邦新手 2 級 ‧ 2013-10-16 11:06:05 檢舉
看了 (ianianwu )的說明.
把SQL語法組出來了,請參考
ps.我用的是 MSSQL 不是MySQL
問題一.
select id
from 
(
select id ,count(id) as cnt
from 
( 
select id from prd1 
union all
select id from prd2 
) as k 
group by id
) as m where cnt=1


問題二的SQL
select id from prd3
except
select id from 
(select id from prd1 
union 
select id from prd2 ) as prd312
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
4
ianianwu
iT邦研究生 5 級 ‧ 2013-09-24 00:23:10
最佳解答

這個在我的鐵人賽中會教到,可惜還不是時候,你可以先參考我簡單敘述的東西,想想看!!
你需要學習外部連結
http://www.1keydata.com/tw/sql/sqlouterjoin.html
然後再利用count+group by方式,當大於1的比數就是重復的,然後再利用曹狀子查詢抓出等於1的資料就可以了

先寫個基礎範例給你看,答案已經完成2/3了,變化的就是外部連結地方自己想想看,學到的就是你的囉!!
我有個my_date的table,裡面有很多日期,我要挑出沒有重復的日期,這樣就可以找出有多少比沒有重復的日期。

<pre class="c" name="code">select count(one_date) from (select count(date) one_date from my_date group by date) where one_date = '1'
4
vigor
iT邦新手 5 級 ‧ 2013-09-24 08:58:19

查詢prd1和prd2共有幾個不同ID
select count(distinct id) from (
select a.id id from prd1
union
select b.id id from prd2
) k

查詢prd3未出現在prd1和prd2
select count(*) from (
select distinct t1.id, t2.id from (
select a.id id from prd1
union
select b.id id from prd2
) t1 left prd3 t2 on t1.id=t2.id
where t2.id is null
) k

4
simon0627
iT邦新手 2 級 ‧ 2013-09-24 12:20:59

查prd3 中id 未於 prd1 及 prd2
select * from prd3 where id not in(select id from prd1,prd2)
但若未有針對的索引及資料多時 會很耗時

相同查不重複產品的id
select id from prd1,prd2 group by id having count(id)=1

我要發表回答

立即登入回答