2012-12-19 35 views
0

我對這個查詢有點問題。它的偉大工程,但我乾的粉絲,這看起來像它可以很容易地加以改進:將查詢保存在變量中,然後添加where子句?

SELECT 
    users.*, 
    (
     SELECT user_information.value 
     FROM users 
     LEFT JOIN user_information 
     ON user_information.userid = users.id 
     WHERE user_information.name = 'account_name' 
    ), 
    (
     SELECT user_information.value 
     FROM users 
     LEFT JOIN user_information 
     ON user_information.userid = users.id 
     WHERE user_information.name = 'account_code' 
    ), 
    (
     SELECT user_information.value 
     FROM users 
     LEFT JOIN user_information 
     ON user_information.userid = users.id 
     WHERE user_information.name = 'account_id' 
    ), 
WHERE ... 

的部分:

SELECT user_information.value 
FROM users 
LEFT JOIN user_information 
ON user_information.userid = users.id 

恰恰是在每個子查詢中的相同(會有將來約有10個子查詢),但where子句每次都會改變。是否有可能將它保存在一個變量中,然後使用它,同時在mysql中追加每個不同的where子句?

回答

1

你可以加入user_information表查詢和分組結果:

SELECT users.*, 
     GROUP_CONCAT(IF(i.name = 'account_name', i.value, NULL)), 
     GROUP_CONCAT(IF(i.name = 'account_code', i.value, NULL)), 
     GROUP_CONCAT(IF(i.name = 'account_id' , i.value, NULL)) 
FROM  users LEFT JOIN user_information AS i ON i.userid = users.id 
WHERE ... 
GROUP BY users.id