2011-07-01 36 views
0

我在一个MySQL数据库中的M2M关系3个表如下:寻找在M2M场景MYSQL不匹配的记录

tbltest (test_id, testdescription) 
tblprofile (profile_id, profiledescription) 
tbltestprofile(testprofile_id,test_id,profile_id) 

我需要从测试表在那里我没有匹配的显示为test_id和说明记录在tbltestprofile和其中profile_id = x

我试过各种组合使用NOT IN但没有所需的结果。任何人都可以协助

+0

您的要求混淆了我。 “testprofile中没有匹配记录”和“profile_id = x”这两个条件如何都为真?这些对我来说似乎是矛盾的。我认为你需要提供更多信息。 – Flimzy

回答

1
SELECT test_id 
    , testdescription 
FROM tbltest AS t 
WHERE NOT EXISTS 
     (SELECT * 
     FROM tbltestprofile tp 
     WHERE t.test_id = tp.test_id 
      AND tp.profile_id = X 
    ) 


旁注。如果您将表格(和字段)的名称保持简单并且不添加tbl前缀(如test,profile,testprofile),将会有所帮助。一个简单的三表加入你可能已经使用:

SELECT tbltest.test_id 
    , tbltest.testdescription 
    , tblprofile.profile_id 
    , tblprofile.profiledescription 
FROM tbltest 
    JOIN tbltestprofile 
    ON tbltest.test_id = tbltestprofile.test_id 
    JOIN tblprofile 
    ON tblprofile.profile_id = tbltestprofile.profile_id 
ORDER BY tblprofile.profiledescription 

让我相当头晕。这不是更好吗?即使没有别名:

SELECT test.id    AS test_id 
    , test.description  AS test 
    , profile.id   AS profile_id 
    , profile.description AS profile 
FROM test 
    JOIN testprofile 
    ON test.id = testprofile.test_id 
    JOIN profile 
    ON profile.id = testprofile.profile_id 
ORDER BY profile.description 
+0

非常感谢。我的实际表格没有tbl前缀。我在上面的例子中给它们加上了前缀,以表明它们是我的3个表格。完全不必要的。有些东西对我来说不太清楚 - 在tbltestprofile tp行末尾tp的意义是什么? – Istari

+0

这是一个别名。 'FROM tbltestprofile tp'与'FROM tbltestprofile AS tp'相同。这不是必需的,我有时忘记把'AS' –

0
SELECT test_id, testdescription 
FROM tbltest 
LEFT JOIN tbltestprofile ON tbltest.test_id = tbltestprofile.test_id 
WHERE tbltestprofile.test_id IS NULL; 
+0

如果您在'ON'条件中添加了'AND tbltestprofile.profile_id = X''',那就等于我的答案。 –

+0

啊......你的回答让他的问题对我有意义。 – Flimzy