swimset_styletag
id swimset_id styletag_id
---------- ---------- -----------
1 1 1
2 2 2
3 3 1
4 3 2
swimset
id set_description
---------- -----------------------
1 4 x 100 Free Interval A
2 4 x 100 Back Interval A
3 6 x 100 free/back on in
styletag
id tag_name
---------- ----------
1 Free
2 back
我正在尝试查询没有styletag 2的游泳集。所以他们只设置返回应该是swimset_id 1.但是,当我尝试使用时:
SELECT swimset_id, set_description, styletag_id
FROM swimset, swimset_styletag, styletag
WHERE
swimset.id = swimset_styletag.swimset_id AND swimset_styletag.styletag_id = styletag.id AND
swimset.styletag_id !=2;
我得到swimset_id 1和3而不仅仅是swimset_id 1.我想这是因为在swimset_styletag中,swimset_id 3有两个条目,一个命中styletag_id 1,另一个命中styletag_id 2.有没有办法同时处理两个swimset_id条目在swimset_styletag作为一个条目?
如果这是应该通过不同的数据库设计解决的问题,我也会接受任何建议,因为我仍在开发精确的设计。当我在没有数据库的情况下对一些python脚本进行原型设计时,我最初使用模拟数据作为True / False值与每个样式标记的键配对。如果我只是将这些样式标签作为True / False条目添加到swimset表中,这将允许一个平面数据库,但似乎更丑陋?是不是那种糟糕的做法而不是有多对多的样式标签?
答案 0 :(得分:3)
我认为这就是你所追求的目标:
SELECT swimset.id, swimset.set_description, swimset_styletag.styletag_id
FROM swimset_styletag INNER JOIN
swimset on swimset_styletag.swimset_id=swimset.id INNER JOIN
styletag on swimset_styletag.styletag_id=styletag.id
WHERE
swimset_id NOT IN (select swimset_id from swimset_styletag WHERE styletag_id=2)
请参阅SQL Fiddle
中的结果删除多个styletag_id
:
SELECT swimset.id, swimset.set_description, swimset_styletag.styletag_id
FROM swimset_styletag INNER JOIN
swimset on swimset_styletag.swimset_id=swimset.id INNER JOIN
styletag on swimset_styletag.styletag_id=styletag.id
WHERE
swimset_id NOT IN (select swimset_id from swimset_styletag WHERE styletag_id IN (2,3,4,5,6))