【问题标题】:MySql SELECT using subqueries don't work as expected使用子查询的 MySql SELECT 不能按预期工作
【发布时间】:2016-07-02 15:35:49
【问题描述】:

我正在创建一个包含多个子查询的选择,但我没有找到一种方法来使用子查询值来创建 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 子句的记录。 仅安慰记录显示正确。

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

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

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

谢谢!!

【问题讨论】:

  • 请提供每个涉及的表的示例数据、您根据该示例从查询中实际获得的输出以及您希望获得的结果。
  • 你为什么不直接说(在第一个)查询t.people is null or t.album is null or t.place = 1?你不需要变量。
  • 感谢 shawnt00!!!!它的作品:) 我为此失去了两天!真的谢谢

标签: mysql select subquery where


【解决方案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
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多