我有一个包含〜35.000.000行的表(MySQL),我需要按ID顺序检索所有数据。
表:数据
+--+-----+-----+
|id|field|value|
+--+-----+-----+
|1 | x | 10 |
+--+-----+-----+
|1 | y | 12 |
+--+-----+-----+
|2 | x | 24 |
+--+-----+-----+
|2 | y | 25 |
+--+-----+-----+
|3 | z | 1 |
+--+-----+-----+
|3 | a | 4 |
+--+-----+-----+
|3 | b | 7.1 |
+--+-----+-----+
我需要检索:
+--+--+----+
|10|12|NULL| <--- ID:1
+--+--+----+
|24|25|NULL| <--- ID:2
+--+--+----+
|1 | 4|7.1 | <--- ID:3
+--+--+----+
我的查询:
SELECT
(
SELECT
value
FROM
data
WHERE
EXISTS(
SELECT
1
FROM
members
WHERE
data.id = members.id
LIMIT 1
)
)
我的结果:
#1241 - Operand should contain 1 column(s)
任何想法如何做到这一点,只有MySQL和高效?
答案 0 :(得分:1)
要获得您在问题中所述的所需输出(单独列中的值),您可以使用此类查询
SELECT r.id,
MAX(CASE WHEN r.rnum = 1 THEN value END) value1,
MAX(CASE WHEN r.rnum = 2 THEN value END) value2,
MAX(CASE WHEN r.rnum = 3 THEN value END) value3
FROM
(
SELECT id, rnum
FROM
(
SELECT DISTINCT id
FROM runnerdata
) d CROSS JOIN
(
SELECT 1 rnum UNION ALL
SELECT 2 UNION ALL
SELECT 3
) n
) r LEFT JOIN
(
SELECT id, value, @n := IF(@g = id, @n + 1, 1) rnum, @g := id
FROM runnerdata
ORDER BY id, data
) q ON r.id = q.id
AND r.rnum = q.rnum
GROUP BY r.id
输出:
| ID | VALUE1 | VALUE2 | VALUE3 | |----|--------|--------|--------| | 1 | 10 | 12 | (null) | | 2 | 24 | 25 | (null) | | 3 | 4 | 7.1 | 1 |
注意: 它不会很快。
这是 SQLFiddle 演示
现在使用GROUP_CONCAT()
您的查询可能看起来像
SELECT id, GROUP_CONCAT(value ORDER BY data) data_values
FROM runnerdata
GROUP BY id
输出:
| ID | DATA_VALUES | |----|----------------| | 1 | 10.00,12.00 | | 2 | 24.00,25.00 | | 3 | 4.00,7.10,1.00 |
这是 SQLFiddle 演示
然后在explode
列的客户端代码data_values
值中迭代结果并生成所需的输出。
答案 1 :(得分:1)
正如你在评论中所说:
i need only value column, but all value column in one row by id.
在这种情况下,您可以使用GROUP_CONCAT功能。我将您的案例简化为最小的工作示例:
mysql> SELECT * FROM data;
+----+-------+
| id | value |
+----+-------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
+----+-------+
5 rows in set (0.00 sec)
SELECT
data.id,
GROUP_CONCAT(data.value)
FROM
data
GROUP BY
data.id;
gives this:
+----+--------------------------+
| id | GROUP_CONCAT(data.value) |
+----+--------------------------+
| 1 | 1,2 |
| 2 | 3,4,5 |
+----+--------------------------+
SQL小提琴暂时不可用,所以给你CREATE TABLE语句:
CREATE TABLE `data` (
`id` int(11) NOT NULL,
`value` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `data` VALUES (1,'1'), (1, '2'),(2,'3'),(2,'4'),(2,'5');