使用子查询的 MySql SELECT 无法按预期工作

标签 mysql select subquery where-clause

我正在创建一个包含多个子查询的选择,但我没有找到使用子查询值来创建似乎被忽略的 where 语句的方法。 我有 1 个内容表、2 个连接表以及另外 2 个连接表,还有另一个表直接与第一个表连接。

我尝试了几种解决方案,这是最新的

select * from (SELECT a.idcontents, a.title, concat(a.filepath, '/', a.filename) as file,
        a.captured_on, a.starred, a.file_type,
        @PL:=(select GROUP_CONCAT(CONCAT(p.idplaces, '-', p.place) SEPARATOR ', ') from places p where a.idplaces=p.idplaces) as places, 
        @AL:=(select GROUP_CONCAT(CONCAT(al.idalbum, '-', al.album) SEPARATOR ', ') from album al, join_album_contents am where am.idalbum=al.idalbum and am.idcontents=a.idcontents) as album, 
        @PE:=(select GROUP_CONCAT(CONCAT(an.idpeople, '-', an.person) SEPARATOR ', ') from people an, join_people_contents ao where ao.idpeople=an.idpeople and ao.idcontents=a.idcontents) as people
        FROM contents a) t
        WHERE (@PE is null OR @AL is null OR @PL=1)

但我也尝试过

SELECT a.idcontents, a.title, concat(a.filepath, '/', a.filename) as file,
        a.captured_on, a.starred, CONCAT(p.idplaces, '-', p.place) as places,
        (select GROUP_CONCAT(CONCAT(al.idalbum, '-', al.album) SEPARATOR ', ') from album al, join_album_contents am where am.idalbum=al.idalbum and am.idcontents=a.idcontents) as album, 
        (select GROUP_CONCAT(CONCAT(an.idpeople, '-', an.person) SEPARATOR ', ') from people an, join_people_contents ao where ao.idpeople=an.idpeople and ao.idcontents=a.idcontents) as people
        FROM contents a, places p
        WHERE a.idplaces=p.idplaces
        and (@album IS NULL OR @people IS NULL or p.idplaces=1)

如果不成功,似乎总是忽略 where 子句,并且结果包含包含一个或所有 where 子句的记录。 唯一值得安慰的是记录正确显示。

只是想知道是否有解决此问题的方案。

在下面的评论中找到了解决方案!!

t.people is null or t.album is null or t.places='1'

谢谢!!

最佳答案

这等效吗?:

SELECT
    a.idcontents, a.title, concat(a.filepath, '/', a.filename) as file,
    a.captured_on, a.starred, a.file_type
FROM contents a
WHERE
        NOT EXISTS (
            select 1
            from people p inner join people_contents pc on pc.idpeople = p.people
            where p.idpeople = a.idcontents /* is this the right column? */
        )
    or  NOT EXISTS (
            select 1
            from album al inner join album_contents ac on ac.idalbum = al.idalbum
            where al.idcontents = a.idcontents
        )
    or  1 = (
            select min(p.idplaces) from places p
            where p.idplaces = a.idplaces
            having count(*) = 1
        )

关于使用子查询的 MySql SELECT 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161759/

相关文章:

css - 选择箭头样式更改

MySQL 子查询 - 最大数量

php - 我如何在codeigniter中调用动态页面内容

mysql - 主键对在两种方式上都是唯一的

mysql - MySQL中存储社区的表结构

javascript - 使用 Javascript 维护一组选择下拉列表

php - 如何使用来自 url 的唯一 ID 选择行

mysql - SQL:从子查询和连接返回不同的相似值时遇到问题

mysql - 嵌套连接查询

php - 在 PHP 中创建分层目录数组