2011-01-23 119 views
0

如何選擇具有精確子對象標識的行?例如,我需要只挑選有subcat_id 2,6或2,4,5,7的行。Mysql複雜選擇

CREATE TABLE IF NOT EXISTS `testing123` (
    `id` int(10) NOT NULL AUTO_INCREMENT, 
    `cat_id` int(10) DEFAULT '0', 
    `subcat_id` int(10) DEFAULT '0', 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=223 DEFAULT CHARSET=utf8; 

REPLACE INTO `testing123` (`id`, `cat_id`, `subcat_id`) VALUES 
    (170, 32, 5), 
    (171, 33, 1), 
    (172, 33, 7), 
    (173, 34, 5), 
    (175, 35, 2), 
    (176, 36, 1), 
    (177, 36, 2), 
    (178, 36, 7), 
    (179, 37, 2), 
    (180, 37, 6), 
    (184, 40, 2), 
    (185, 40, 5), 
    (186, 40, 6), 
    (187, 41, 4), 
    (188, 54, 2), 
    (189, 54, 4), 
    (190, 54, 5), 
    (191, 54, 7), 
    (192, 55, 6), 
    (193, 56, 2), 
    (194, 56, 6), 
    (195, 57, 6), 
    (196, 58, 1), 
    (197, 59, 3), 
    (198, 60, 6), 
    (199, 61, 2), 
    (200, 61, 6), 
    (203, 63, 1), 
    (204, 63, 6), 
    (205, 64, 2), 
    (206, 64, 6), 
    (207, 65, 1), 
    (208, 65, 2), 
    (209, 66, 4), 
    (214, 67, 1), 
    (215, 67, 5), 
    (220, 70, 1), 
    (221, 70, 4), 
    (222, 70, 5); 

如果我使用或OR(),它的採摘所有的行,即有任何一個提供subcats,但我需要只有完全匹配。

爲實驗提供的表格示例。

幫助! :)

+0

中列舉了你能解釋一下你的已經subcat_id 2,6或2,4,5,7是什麼意思? subcat_id只是一個整數,所以沒有一行會有一個由兩個或更多個組成的subcat_id。 – Arkaaito 2011-01-23 09:58:07

+0

真的嗎?請看下面的答案。 :) – Somebody 2011-01-23 10:14:14

回答

2
SELECT * 
    FROM testing123 
WHERE cat_id IN (SELECT cat_id 
        FROM testing123 
        WHERE subcat_id IN (2, 6) 
       GROUP BY cat_id 
        HAVING COUNT(*) = 2) 


SELECT * 
    FROM testing123 
WHERE cat_id IN (SELECT cat_id 
        FROM testing123 
        WHERE subcat_id IN (2, 4, 5, 7) 
       GROUP BY cat_id 
        HAVING COUNT(*) = 4) 

注意COUNT(*) = N條款取決於有多少subcats在IN()