0

我对这个查询有点问题。它工作得很好,但我是 DRY 的粉丝,这看起来很容易改进:

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子句时使用它?

4

1 回答 1

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
于 2012-12-19T11:20:56.953 回答