SQL子查询获取外部查询的更多行

时间:2016-03-10 15:54:20

标签: mysql sql

我试图想出一种从不同的表中获取两个数据集的方法。这是SQL的工作版本

SELECT l.id AS teamId, l.leagueId, t.name AS teamName, a.id
FROM leagues AS l
LEFT JOIN (
    SELECT a.id, a.teamId
    FROM activities AS a
    WHERE a.status=(:a) AND a.leagueId=(:l) 
        AND a.apply_standings=(:p) AND a.activityCode = (:g) 
) on a.teamId = l.teamId
JOIN teams AS t ON t.id = l.teamId
WHERE l.status !=(:s) AND l.leagueId=(:l)
ORDER BY teamId
LIMIT 55


TABLES
Teams
+-----------+-----------+
|   id      |   name    |                                                           
+-----------+-----------+
1             Scorpions
2             Jazz  
...

League
+------------+-----------+
|   leagueId |  teamId   |                                                            
+------------+-----------+
1               2
1               1
2               1
3               4
...

Activities
+-----------+----------------+---------+
|   id      |   activityCode |  teamId |                                                    
+-----------+----------------+---------+
1               game            1
2               social          2
3               ..              1
4               ..              3
...

此查询的问题是,如果有更多活动,那么查询将只返回一个结果。我试图将上述语句转换为所选各种语句的子查询但我点击SQLSTATE [21000]:基数违规:1241操作数应包含1列错误。

基本上我试图得到与此类似的结果

array(
    "team_name",
          array(
              ..activity details
          ),
          array(
              ..activity details
          ),
          array(
              ..activity details
          ),
),
    "other Name",
          array(
              ..activity details
          ),
          array(
              ..activity details
          ),
          array(
              ..activity details
          ),
);

我知道这不是我会收到的格式,但这是我能想到的最好的代表。

1 个答案:

答案 0 :(得分:0)

所以,如果我理解正确,你想:

  • 所有拥有team_id的club_member条目
  • 只有符合某些约束的条目(联盟,状态,排名,活动代码?)
  • 然后获取这些条目的所有活动(如果有的话)。
  • 这些活动的所有结果? (不确定这一个)
  • 列出teamId的结果

另外,请原谅任何语法问题,我不像其他SQL引擎那样熟悉MySQL。

SELECT 
    cm.id AS teamId, cm.leagueId, t.name AS teamName, a.id, 
    a.homeId, a.awayId, a.score_away, a.score_home
FROM `clubs-members` AS cm
JOIN teams AS t ON t.id = cm.teamId
LEFT JOIN activities AS a ON (a.teamId = cm.teamId AND a.status=(:a) 
     AND a.apply_standings=(:p) AND a.activityCode = (:g) )
LEFT JOIN `activities-results` AS r ON r.activityId = a.id AND UNIX_TIMESTAMP(r.approved) != 0
WHERE cm.status !=(:s) AND cm.leagueId=(:l)
ORDER BY teamId
LIMIT 55

如果这让你到达你想去的地方,请告诉我。