我建議的一些方法:
3-第三之一:(工程並標記爲答覆)
SELECT tbl.id_px FROM
(SELECT id_px ,
SUM(id_category NOT IN (1,32)) as b ,
SUM(id_category = 1) as t1 , SUM(id_category = 32) as t2
FROM my_table
GROUP BY id_px) as tbl
WHERE tbl.b = 0 AND tbl.t1 = 1 AND tbl.t2 = 1
4-重新構建查詢-2:
4.1第一步驟的重建:(低效)
SELECT tbl.id_px FROM
(SELECT id_px , CONCAT('-,' , GROUP_CONCAT(id_category),',') as gr
FROM my_table
GROUP BY id_px
) as tbl
WHERE
INSTR(tbl.gr , ',1,' )>0
AND INSTR(tbl.gr , ',32,')>0
AND LENGTH(tbl.gr)-LENGTH(REPLACE(REPLACE(tbl.gr,',1,' ,''), ',32,' ,'')) = LENGTH(CONCAT(',1,' , ',32,'))
在012最後的條件從tbl.gr
替換1和32以及比較減少LENGTH
如果減小的長度等於1和32串,有僅1和32,從而重寫查詢以這一個:
4.2-新可能工作查詢:(簡化)
SELECT tbl.id_px FROM
(SELECT id_px , GROUP_CONCAT(id_category) as gr
FROM my_table
GROUP BY id_px
) as tbl
WHERE
tbl.gr = '1,32' or tbl.gr = '32,1'
沒有任何樣本數據看來這是好的,但同時問題是限制id_category恰好有兩個值,並沒有其他id_category他們沒有很好的答案。
注:這兩個查詢,選擇id_px
有id_category
1,32,也許許多其他id_category,所以這些都不是可以接受的答案對這個問題
2 - 選擇id_px
通過join
SELECT a.id_px
FROM my_table as a
LEFT JOIN my_table as b
ON a.id_px = b.id_px
WHERE a.id_category = 1 AND b.id_category = 32
GROUP BY a.id_px
1-使用group by
並在id_px
中搜索:
SELECT tbl.id_px FROM
(SELECT id_px , CONCAT('-,' , GROUP_CONCAT(id_category),',') as gr
FROM my_table
GROUP BY id_px
) as tbl
WHERE
INSTR(tbl.gr , ',1,' )>0
AND INSTR(tbl.gr , ',32,')>0
不能在第一個查詢中使用OR嗎?據我瞭解,你只需要具有id_category特定值的記錄。 – smb564
不是因爲我需要你有兩個具體。不是,如果你有一個。我需要你有兩個具體的ID。 –
您是否可以更新您的問題並添加適當的數據樣本和預期結果? – scaisEdge