2017-05-08 25 views
0

我在特定查詢時遇到了一些麻煩。假設你有一個像eBay的網站,並且要選擇出售至少2個對象的用戶,但它們是不同類型的(衣服,電子產品等)的使用MySQL將2列子查詢轉換爲1

這裏是我想出了:

Select name, count(id_object) from user u,advert a where u.id_user=a.id_seller and 
a.id_buyer IS NOT NULL and 
id_object in (select o1.id_object, o2.id_object from object o1, object o2 
where o1.id_object != o2.id_object and o1.type_object != o2.type_object) 
group by name 
having count(id_object)>1 

問題發生在這裏:

id_object in (select o1.id_object, o2.id_object from object o1, object o2 
where o1.id_object != o2.id_object and o1.type_object != o2.type_object) 

這不起作用,因爲我拉從子2列選擇並id_object是唯一的一個。

我的第二次嘗試涉案分離object1和對象2,但因爲他們需要的是不同的「在」收益沒有增加。

我的第三個嘗試是從UNION對象1和2的結果,但我沒能放置一個限制上的object1必須從objet2不同的事實。

如果有幫助,這裏是表的簡化架構:

Object (id_object, type_object) 
Advert (id_seller, id_buyer, id_object) 
User (id_user, name) 

我也搜索了類似的問題計算器沒有任何成功: MySQL: Using "In" with Multiple SubQueries? MySQL: Returning multiple columns from an in-line subquery

回答

1

的我會做如:

select a.id_user 
from advert a join 
    object o 
    on a.id_object = o.id_object 
group by a.id_user 
having count(distinct o.type_object) > 1; 

由於對象可以僅具有一種類型,這滿足標準。您也可以添加and count(distinct o.id_object) > 1,但這是多餘的。

如果您需要更多的用戶信息,那麼您可以加入該表,或使用in或使用exists

1

嘗試這樣的事情。

編輯:媽忘了這類型的事情,請嘗試以下。 編輯2:我們不想要相同類型的對象,但不同。請再試一次,慢慢變醜。 編輯3:固定出現次數

Select * from user where id_user in (
    Select c.id_seller from (
     Select a.id_seller as id_seller, 
       o.object_type as oject_type, 
       count(*) as numOccurrences 
     from adverts a, object o 
    where o.id_object=a.id_object 
    group by a.id_seller having count(*) > 1) c 
where c.numOccurrences > 1); 
+0

您的查詢有效,但會返回僅出售同一類型兩次的用戶的姓名。我想知道爲什麼發生這種情況,因爲你的小組似乎罰款 – Maude

+0

你是完全正確,編輯再次,希望現在好了:-) – LSA

+0

有一些問題,與此部分: '選擇a.id_seller爲id_seller,o.object_type如從廣告oject_type一個,對象o其中o.id_object = a.id_object由具有計數a.id_seller(*)> 1' 當我通過刪除該組時,得到與賣家他們銷售的所有類別組。到現在爲止還挺好。但是,當我通過賣方申請該組時,他選擇了賣家ID,但只選擇了一種類型的對象。他不保留第二個。所以c.object_type = = 1不起作用。 Putting = 1而不是> 1的作品,但我想知道它是否適用於我需要的每種情況? – Maude