我做了一个查询,我从表X
id | name | created | modified
-----------------------------------------------------------
2 | Film1 | 2016-01-29 06:00:09 | 2016-01-29 06:00:10
5 | Film1 | 2016-01-27 06:00:09 | 2016-01-27 06:00:10
7 | Film1 | 2016-01-23 06:00:09 | 2016-01-23 06:00:10
1 | Film2 | 2016-01-26 06:00:09 | 2016-01-26 06:00:10
8 | Film2 | 2016-01-28 06:00:09 | 2016-01-28 06:00:10
9 | Film2 | 2016-01-29 06:00:09 | 2016-01-29 06:00:10
我有一张表Y
,我在其中获取每个重复值的照片数量:
id | name | num_photos |
--------------------------------------------
2 | Film1 | 20 |
5 | Film1 | 10 |
7 | Film1 | 12 |
1 | Film2 | 20 |
8 | Film2 | 50 |
9 | Film2 | 12 |
如何使用更多数量的照片复制?在php数组中?
结果:
id | name | num_photos |
---------------------------------------
2 | Film1 | 20 |
8 | Film2 | 50 |
答案 0 :(得分:2)
可能是这样的:
select * from (select * from y order by num_photos desc) sub group by name
请根据您的需要调整一下。
答案 1 :(得分:2)
创建表/插入数据
CREATE TABLE Y
(`id` INT, `name` VARCHAR(5), `num_photos` INT)
;
INSERT INTO Y
(`id`, `name`, `num_photos`)
VALUES
(2, 'Film1', 20),
(5, 'Film1', 10),
(7, 'Film1', 12),
(1, 'Film2', 20),
(8, 'Film2', 50),
(9, 'Film2', 12)
;
这样做有两种方法。
使用用户变量。
<强>查询强>
SELECT
y.id
, y.name
, y.num_photos
FROM ( SELECT @name := '') AS init_user_var
CROSS JOIN (
SELECT
*
, (y.name != @name) AS firstInGroup
, @name := y.name
FROM
Y
ORDER BY
Y.name ASC
, Y.num_photos DESC
)
AS
Y
WHERE
y.firstInGroup = 1
ORDER BY
Y.id ASC
<强>结果强>
id name num_photos
------ ------ ------------
2 Film1 20
8 Film2 50
使用max和group by以及join来传递表。
<强>查询强>
SELECT
y.*
FROM (
SELECT
y.name
, MAX(y.num_photos) max_num_photos
FROM
Y
GROUP BY
y.name
) AS
y_max_num_photos
INNER JOIN
Y
ON
Y.name = y_max_num_photos.name
AND
Y.num_photos = y_max_num_photos.max_num_photos
ORDER BY
y.id ASC
<强>结果强>
id name num_photos
------ ------ ------------
2 Film1 20
8 Film2 50
答案 2 :(得分:-2)
尝试以下查询。
SELECT DISTINCT(name) as name, (select max(num_photos) from Y) as num_photos, id FROM Y;