2013-04-25 69 views
2

以下查詢用於提取以下列&行。如何爲每個唯一用戶標識提取兩行

問題是我不能從每個用戶ID提取兩行。 如果我使用的限制,然後只提取前兩行。

所以我如何可以爲每個唯一用戶ID提取兩行。

例如:

two rows of userid 222 
two rows of userid 122 
two rows of userid 367 

TEXT OP:

預期輸出:

+0

你需要什麼輸出? – 2013-04-25 07:05:14

+0

您是否可以將查詢中的** text **輸出複製並粘貼到問題中? – 2013-04-25 07:17:56

+0

請檢查圖像鏈接。 – ASD 2013-04-25 07:19:04

回答

0

假設ID是你的用戶ID和POST_ID是獨一無二的。

(SELECT id,name,post,Image,post 
    FROM users 
    GROUP BY id 
    ORDER BY id 
) 
UNION 
(SELECT id,name,post,Image,post 
    FROM users 
    WHERE post_ID NOT IN 
    (SELECT post_ID 
    FROM users 
    GROUP BY id 
    ORDER BY id) 
    GROUP BY id 
    ORDER BY id 
) 
ORDER BY id, post_ID 

請檢查我的查詢從中我得到的答案如下:

(
SELECT store_id, `key_id` , `string` , `translate` , `locale` 
FROM `core_translate` AS C 
GROUP BY `store_id` 
ORDER BY `store_id` 
) 
UNION (

SELECT store_id, `key_id` , `string` , `translate` , `locale` 
FROM `core_translate` AS C 
WHERE `key_id` NOT 
IN (

SELECT `key_id` 
FROM `core_translate` AS C 
GROUP BY `store_id` 
ORDER BY `store_id` 
) 
GROUP BY `store_id` 
ORDER BY C.`store_id` 
) 
ORDER BY store_id, `key_id` 

store_id key_id string translate locale 
0 20 Screensize Screensize en_US 
0 21 Gender Gender en_US 
1 1 Size Size en_US 
1 2 Color Color en_US 
2 5 Large Image  Large Image  en_US 
2 6 Medium Image Medium Image en_US 
3 10 Manufacturer Manufacturer en_US 
3 11 Dimensions Dimensions en_US 
4 15 Description  Description  en_US 
4 16 Weight Weight en_US 
+0

使用DISTINCT它實際上只顯示前兩行。我試圖爲每個用戶提取兩行。 – ASD 2013-04-25 07:14:05

+0

請檢查修改後的答案。 – 2013-04-25 08:13:09

+0

謝謝..我能夠只提取一行用戶。 – ASD 2013-04-25 08:24:08

0

不知道這是在MySQL可行的,但你能這樣。 我假設id是用戶ID和post_ID是唯一的。

編輯

嘗試要解決MySQL的限制。

select id,name,post_Imagename_small,Image_title,post_ID from users u1 
where u1.post_ID in (
    select u3.post_ID from (
     select u2.post_ID from users u2 
     where u2.id = u1.id 
     limit 2 
    ) s u3 
) 
order by u1.id 

EDIT 2

中,答案不工作的情況下,here是這類查詢問題的一個良好的閱讀,有很多種解決技術途徑了。

+0

這個版本的MySQL還不支持任何其他解決方案的'LIMIT&IN/ALL/ANY/SOME子查詢'嗎? – ASD 2013-04-25 07:16:53

+0

介意試試我的編輯?我目前無法訪問任何MySQL數據庫。 – viclim 2013-04-25 07:31:50

+0

@ASD:您使用的是哪個版本的MySQL? – 2013-04-25 07:33:24

相關問題