SQL子查询空返回

时间:2012-01-26 13:23:52

标签: sql subquery

我很抱歉这个头衔,但我找不到更好的头衔。 我的问题如下: 我想从表“log”中选择所有字段,其中字段“user”是“user1”或“user2 in”friendships“。我的查询看起来像这样,但它返回零值:

    SELECT * FROM `log` 
    WHERE `user` = ANY(SELECT `user1` FROM `friendships` 
                       WHERE (`user1` = 1 OR `user2` = 1) AND `active` = 1) 
    OR `user` = ANY(SELECT `user2` FROM `friendships` 
                    WHERE (`user1` = 1 OR `user2` = 1) AND `active` = 1) 
    GROUP BY `arguments` 
    ORDER BY `created` DESC

如果我只使用一个子查询,它可以工作,但我也需要第二个字段。还有更多的值(这就是我使用ANY而不是JOIN的子查询的原因)。 我希望有人发现我的错误:)。

3 个答案:

答案 0 :(得分:3)

我希望这有效:

SELECT *
FROM `log` INNER JOIN `friendships` on
    `log`.`user` = `friendships`.`user`
WHERE `friendships`.`user` in (1,2)
            AND
      `friendships`.`active` = 1
ORDER BY `created` DESC

PS:可以发布表格的架构(或结构)吗?

更新1

SELECT *
FROM
(
    SELECT *
    FROM `log` INNER `friendships` on
        `log`.`user` = `friendships`.`user1`
    WHERE `friendships`.`user1` in (1,2) 
            AND
          `friendships`.`active` = 1
    UNION
    SELECT *
    FROM `log` INNER `friendships` on
        `log`.`user` = `friendships`.`user2`
    WHERE `friendships`.`user2` in (1,2) 
            AND
          `friendships`.`active` = 1
) as iTable
ORDER BY iTable.`created` DESC

答案 1 :(得分:1)

我可能会尝试不同的方法,也许这样:

SELECT *
FROM `log`
WHERE `user` IN (
  SELECT `user1` FROM `friendships` WHERE `user2` = @user AND `active` = 1

  UNION ALL

  SELECT `user2` FROM `friendships` WHERE `user1` = @user AND `active` = 1

  UNION ALL

  SELECT @user
)
GROUP BY
  `arguments`
ORDER BY
  `created` DESC

虽然说实话,我会避免在这样的查询中选择既不聚合也不包含在GROUP BY中的列,即使MySQL允许我这样做。

另一种选择:

SELECT *
FROM `log`
WHERE `user` IN (
  SELECT
    CASE `user1` WHEN @user THEN `user2` ELSE `user1` END AS `user`
  FROM `friendships`
  WHERE (`user1` = @user OR `user2` = @user) AND `active` = 1

  UNION ALL

  SELECT @user
)
GROUP BY
  `arguments`
ORDER BY
  `created` DESC

答案 2 :(得分:1)

使用union将OR重构为单个列表:

select * 
from `log` 
where `user` in (
    select user1
    from friendships 
    where user1 in (1, 2) and active)
    union
    select user2
    from friendships 
    where `user1` in (1, 2) and active
)
group by arguments
order by `created` desc

或在标准联接上使用联合

select * from (
select l.* 
from `log` l
join friendships f on l.user = f.user1 and f.user1 in (1, 2) and f.active
union
select l.* 
from `log` l
join friendships f on l.user = f.user2 and f.user2 in (1, 2) and f.active
) x
group by arguments
order by `created` desc