我对此查询有点问题。它运作得很好,但我是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子句时使用它?
答案 0 :(得分: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