我有一个表,其中包含具有相同标题的产品的多个实例的产品信息,由不同的颜色和它们的id标识。我需要输出整个行,其中id =按标题分组的最大id,但我似乎无法让它这样做。下面是一个非常简化的表格和一些示例数据:
id title colour description
1 rico red blah1
2 rico blue blah2
3 rico yellow blah3
4 katia black blah4
5 katia white blah5
在我的代码示例中,当我想要3个黄色blah3时,我得到了1个红色blah1。
下面是我使用的代码:SELECT pd_id, pd_title, pd_description, pd_colour,
pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new
FROM product
WHERE
cat_sub_id_1 = '".$cat_sub_id."'
AND cat_parent_id='".$cat_parent_id."'
GROUP BY pd_title
HAVING MAX(pd_id)
ORDER BY pd_id DESC
更新:谢谢大家,
我使用alinoz的答案来编写以下有效的代码:)
SELECT
pd_id,pd_title,pd_description,pd_colour,pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new
FROM product
HERE cat_sub_id_1 = '".$cat_sub_id."' AND cat_parent_id='".$cat_parent_id."'
AND pd_id IN (
SELECT max(pd_id)
FROM product
WHERE cat_sub_id_1 = '".$cat_sub_id."' AND cat_parent_id='".$cat_parent_id."'
GROUP BY pd_title
)
GROUP BY pd_title
ORDER BY pd_id DESC
啊啊啊,最伟大的一群人…
select *
from YourTable yt
inner join(
select title, max(id) id
from YourTable
group by title
) ss on yt.id = ss.id and yt.title = ss.title
当然,您应该根据您的需要相应地调整它。
另外,我认为这是一个"必须阅读":SQL只选择列上具有最大值的行
我认为这可能会起作用(未测试):
SELECT * FROM that_table WHERE id IN (
SELECT MAX(id) FROM that_table GROUP BY title
) /* AND this = that */
仅为任意一行(在本例中为'id')的最大值
SELECT * FROM `your_table` order by id desc limit 1
尝试添加一个子句到您的where与pd_id = (select max(pd_id) from…)
SELECT pd_id, pd_title, pd_description, pd_colour,
pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new
FROM product
WHERE
cat_sub_id_1 = '".$cat_sub_id."'
AND cat_parent_id='".$cat_parent_id."'
AND pd_id = (select max(pd_id) from product)
GROUP BY pd_title
这个查询不是最优的,但它可以完成工作。
除了Adrian和Salman的方法之外,还有一个方法,当有平局时,两个或更多具有相同(最大)id的行时,它会给出不同的结果。它将只显示每个标题的一行,而另一个查询将显示所有的(在您的情况下,这可能是不相关的,因为您按id排序,我认为是主键):
SELECT
t.*
FROM
TableX AS t
JOIN
( SELECT DISTINCT
title --- what you want to Group By
FROM TableX
) AS dt
ON t.PK = --- the Primary Key of the table
( SELECT tt.PK
FROM TableX AS tt
WHERE tt.title = dt.title
ORDER BY id ASC --- (or DESC) what you want to Order By
LIMIT 1
)
既然已经排序了,那么可以在where条件中使用行号=1。请看这个链接。既然你的数据库不为人所知。我不能给出一个具体的问题,但给你指明方向
或尝试SQL top,将产生相同的结果,因为order by使用
我认为没有必要使用subselect:
select
SUBSTRING_INDEX(group_concat(testtab.ActionID order by testtab.ActionID DESC SEPARATOR '|'), '|', 1) as ActionIDs,
SUBSTRING_INDEX(group_concat(testtab.DiscountedPrice order by testtab.ActionID DESC SEPARATOR '|'), '|', 1) as DiscountedPrices
testtab.*
from testtab
where
testtab.StartDate <= 20160120
and testtab.EndDate > 20160120
and testtab.VariantID = 302304364
and testtab.DeleteStatus = 0
group by testtab.VariantID
order by testtab.VariantID, testtab.ActionID;
这只是一个快速的例子从我的测试。只需按相同的方式在substring_indexes中排序,并使用一个好的分隔符。
玩