2016-09-06 84 views
-1

我有一個像每個產品具有多個相同值的數據庫,並且我想在上面顯示MAX相同的值產品。如何在MYSQL中使用MAX獲取具有相同記錄的產品

Example: 

title   product    category 

jack   nnn33    books 
tom   nnn33    books 
jay   vvv34    books 
dex   lxxx3    books 
rio   nnn33    books 
james   nnn33    books 

我想顯示nnn33作爲最大值記錄在上面。

查看下面的查詢。

$query = mysqli_query($conn, 
    "SELECT id,title,product,category FROM data WHERE category = 'Books' ORDER BY MAX(product) DESC LIMIT 10"); 
+0

最大字符串或計數? – Drew

+0

通過計數得到最大的內部派生,然後外部循環首先顯示他們? – Drew

+0

一個字符串的最大值'nnn33'多次具有相同值的產品應該位於頂部 – Aliza

回答

2

最大計數物品列表第一,減少計數跟隨。

架構

create table myTable7 
( title varchar(100) not null, 
    product varchar(100) not null, 
    category varchar(100) not null 
); 
insert myTable7 values 
('jack',   'nnn33',    'books'), 
('tom',   'nnn33',    'books'), 
('jay',   'vvv34',    'books'), 
('dex',   'lxxx3',    'books'), 
('rio',   'nnn33',    'books'), 
('james',   'nnn33',    'books'); 

查詢

select t7.title,t7.product,t7.category 
from 
( select product,count(*) as theCount,@rownum:[email protected]+1 as theOrder 
    from mytable7 
    cross join (select @rownum:=0) xParams 
    group by product 
    order by theCount desc 
) d 
join mytable7 t7 
on t7.product=d.product 
order by d.theOrder,t7.title; 
+-------+---------+----------+ 
| title | product | category | 
+-------+---------+----------+ 
| jack | nnn33 | books | 
| james | nnn33 | books | 
| rio | nnn33 | books | 
| tom | nnn33 | books | 
| jay | vvv34 | books | 
| dex | lxxx3 | books | 
+-------+---------+----------+ 
6 rows in set (0.00 sec) 
+0

選擇中的計數似乎是不必要的 – Strawberry

+0

它不在最終輸出中。有必要根據操作要求 – Drew

+0

我不這麼認爲。 – Strawberry

相關問題