2

我有两个查询,我想是否可以仅在一个查询中作为 Select 中的 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。

是否可以在一个查询中执行所有操作,并在选择中进行选择?

提前感谢您的帮助

4

2 回答 2

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由于在匹配条件中,在没有相关子查询的情况下执行此操作有点挑战性。

于 2013-05-31T22:14:47.770 回答
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
于 2013-05-31T18:28:19.840 回答