在Select MySQL中选择

时间:2013-05-31 18:22:38

标签: mysql multi-select

我有两个查询,我想是否可以只在一个查询中执行Select in Select。

第一个:

SELECT
users.id
FROM users
LEFT JOIN users_date ON users_date.user = users.id
LEFT JOIN users_varchar ON users_varchar.user = users.id
WHERE
abilitato = 1 
AND users_date.key = 'birthday'
AND users_varchar.key = 'nation'
AND users_varchar.value = 'US'
AND (users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31')
AND (floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19)

它检索用户ID列表(按年龄,国家或注册日期过滤)

第二个:

SELECT count(`matches`.`id`) FROM `matches` WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3) AND (`matches`.`team_home` = 13 OR `matches`.`team_guest` = 13)

我需要对一个人检索到的每个ID执行第二次选择。 对于每个执行,我必须用检索到的id替换值13。

可以在一个查询中执行所有选择吗?

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

试试这个sql。

SELECT count(`matches`.`id`) 
FROM `matches` m
INNER JOIN ( SELECT users.id as id
FROM users
LEFT JOIN users_date ON users_date.user = users.id
LEFT JOIN users_varchar ON users_varchar.user = users.id
WHERE abilitato = 1 
AND users_date.key = 'birthday'
AND users_varchar.key = 'nation'
AND users_varchar.value = 'US'
AND (users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31')
AND (floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19)) t
on t.id=m.team_guest
WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3) 
AND (`matches`.`team_home` = 13 OR `matches`.`team_guest` = t.id)
GROUP BY t.id

答案 1 :(得分:0)

您可以将您想要做的事情表达为明确的联接。但问题是要求选择中的选择。为此,您需要一个相关的子查询。这是最终查询:

select users.id,
       (SELECT count(`matches`.`id`)
        FROM `matches`
        WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3) AND 
              (`matches`.`team_home` = user.id OR `matches`.`team_guest` = users.id)
       ) as cnt
FROM users LEFT JOIN
     users_date
     ON users_date.user = users.id LEFT JOIN
     users_varchar
     ON users_varchar.user = users.id
WHERE abilitato = 1 AND users_date.key = 'birthday' AND
      users_varchar.key = 'nation' AND users_varchar.value = 'US' AND
      (users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31') AND
      (floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND
       floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19
      )

(格式化有助于我更好地理解查询。)

由于匹配条件中的or,在没有相关子查询的情况下执行此操作有点挑战。