我有3个表:picsfolderspics_by_folders

图片

 pic_ID | name | info


资料夹

folder_ID | name | info


pics_by_folders

folder_ID | pic_ID


我试图返回所有满足要求x,y,z的pics,但前提是它们都包含在满足要求j,k,l的文件夹中。我希望我以一种有意义的方式对此进行解释。我当前的声明是:

SELECT * FROM pics WHERE
              pic_ID = 'x' AND
              pics.name = 'y' AND
              pics.info = 'Z'
JOIN pics_by_folder as pbf ON
              pbf.pic_ID = pics.pic_ID
JOIN folders WHERE
              folder_ID = 'j' AND
              folders.name = 'k' AND
              folders.info = 'l'
ON
              folders.folder_ID = pbf.folder_ID


这是行不通的,我认为它与语句的顺序有关,或者sql不允许"JOIN x WHERE ..."语句。无论哪种方式,任何帮助将不胜感激。

最佳答案

语法错误!

SELECT
 *
FROM pics
JOIN pics_by_folder as pbf ON pbf.pic_ID = pics.pic_ID
JOIN folders ON folders.folder_ID = pbf.folder_ID
WHERE folder_ID = 'j' AND
   folders.name LIKE 'k' AND
   folders.info LIKE 'l' AND
   pic_ID LIKE 'x' AND
   pics.name LIKE 'y' AND
   pics.info LIKE 'Z'


一些注意事项:

请始终指定要在结果集中使用的列。否则,您将感到困惑,因为您不知道结果集中将有多少列。

folders.name LIKE 'k'等效于folders.name = 'k'

如果要精确匹配,请使用folders.name ='k',否则使用通配符%,如下所示:
folders.name LIKE '%k%'

关于php - 编写一条sql语句以根据其他表中的列查询一个表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38639281/

10-10 22:03