2013-05-31 163 views
2

我有兩個查詢,我想如果可能只在一個查詢中執行爲Select in Select。在選擇MySQL中選擇

第一個:

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。

它有可能執行所有在一個單一的查詢select select?

感謝您的進一步幫助

回答

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 
+0

有問題 你建議的INNER JOIN,但ON子句是錯誤的:( 的t.id值可以是在team_home場或team_guest場 我還必須有一個參數值改變team_home = 13 – Zauker

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的一個挑戰。