加入SQL请求

时间:2016-08-20 18:46:57

标签: sql join request

我的sql请求中存在连接问题。

我有两个数据库:

  
      
  • 首先:我存储图像(id,文件名)
  •   
  • 第二:在我的网站上,一些用户被禁止看到一些图像。我也存储在这个数据库中(id_image,id_user)。
  •   

如果用户没有出现在第二个数据库中,他可以看到图像。

现在我想请求用户列出他允许查看的所有图像。

这是我的实际要求(这是错误的)。

SELECT 
      pi.filename, 
FROM 
    image AS pi
INNER JOIN 
    images_forbidden AS pii
ON 
    pi.id = pii.id_image AND pii.id_user = 10

你能帮助我吗?

4 个答案:

答案 0 :(得分:1)

使用left join

SELECT pi.filename
FROM image AS pi 
LEFT JOIN images_forbidden AS pii ON pi.id = pii.id_image 
                                 AND pii.id_user = 10
WHERE pii.id_image IS NULL

答案 1 :(得分:1)

您想要找到匹配的图片。 LEFT JOIN是一种方法:

SELECT pi.filename, 
FROM image pi LEFT JOIN 
     images_forbidden pii
     ON pi.id = pii.id_image AND pii.id_user = 10
WHERE pii.id_image IS NULL;

另一种常用方法是使用NOT INNOT EXISTS

SELECT pi.filename
FROM image pi
WHERE NOT EXISTS (SELECT 1
                  FROM images_forbidden pii
                  WHERE pi.id = pii.id_image AND pii.id_user = 10
                 );

答案 2 :(得分:1)

您可以使用WHERE NOT EXISTS之类的

SELECT 
      pi.filename
FROM 
    image AS pi
WHERE NOT EXISTS (SELECT 1 FROM images_forbidden 
              WHERE pi.id = id_image 
                    AND id_user = 10)

答案 3 :(得分:0)

您可以使用NOT IN来实现此目的而不是JOIN

SELECT  filename
  FROM  image
  WHERE (id NOT IN ( SELECT  id_image
                       FROM  images_forbidden
                       WHERE (id_user = 10)))

此代码从filename表中选择image表中id不在用户10的id_image列表中的所有import re f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r') val_dict = {} for line in f: k, v = line.strip().split('=') val_dict[k.strip()] = v.strip() f.close() print val_dict h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r') str_list = [] for line in h: str_list.append(str(line).strip()) print str_list tmp_str = '' for val in str_list: tmp_str = val for k in val_dict.keys(): if k in val: replace_str = str(val_dict[k]).strip() + "," tmp_str= re.sub(r'\b{0}\b'.format(k),replace_str,tmp_str,flags=re.IGNORECASE) tmp_str = tmp_str.strip(",") print val, " = ", tmp_str tmp_str = ''