【发布时间】:2019-06-20 00:32:24
【问题描述】:
我正在尝试从 JOINed 表中选择唯一行
(忽略任何重复项,除了符合条件的重复项)
其中重复由在列post_title 中具有相同值的记录定义
将选择每个重复集中_meta_value 列中具有最低值的行。如果是 2 行之间的平局,则只需选择最低的行 post_ID 或 ID(唯一)。
到目前为止,这就是我所拥有的 - 它不起作用(返回零行) - 虽然意图应该很清楚,但我确定我没有使用正确的功能。
SELECT * FROM (
select wp_posts.ID, wp_posts.post_title, wp_postmeta.post_id, wp_posts.post_type, wp_postmeta.meta_key, wp_postmeta.meta_value
from wp_postmeta JOIN wp_posts
ON wp_postmeta.post_ID=wp_posts.ID
WHERE post_type = 'product' AND meta_key = '_regular_price'
GROUP BY post_title
) as alias1
HAVING MIN(meta_value)
ORDER BY post_title
这是两个表的JOIN 之后请求的最小数据样本:
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
| wp_posts.ID | wp_posts.post_title | wp_postmeta.post_id | wp_posts.post_type | wp_postmeta.meta_key | wp_postmeta.meta_value |
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
| 1 | Apple Pie | 1 | Product | _regular_price | 10 |
| 2 | French Toast | 2 | Product | _regular_price | 5 |
| 3 | Shepards Pie | 3 | Product | _regular_price | 9 |
| 4 | Jam Pie | 4 | Product | _regular_price | 8 |
| 5 | Jam Pie | 5 | Product | _regular_price | 11 |
| 9 | French Toast | 9 | Product | _regular_price | 12 |
| 10 | French Toast | 10 | Product | _regular_price | 12 |
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
查询应该返回:
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
| wp_posts.ID | wp_posts.post_title | wp_postmeta.post_id | wp_posts.post_type | wp_postmeta.meta_key | wp_postmeta.meta_value |
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
| 1 | Apple Pie | 1 | Product | _regular_price | 10 |
| 2 | French Toast | 2 | Product | _regular_price | 5 |
| 3 | Shepards Pie | 3 | Product | _regular_price | 9 |
| 4 | Jam Pie | 4 | Product | _regular_price | 8 |
+-------------+---------------------+---------------------+--------------------+----------------------+------------------------+
【问题讨论】:
-
MySql 5.x 还是 8.x?我问这个是因为使用像 ROW_NUMBER 这样的窗口函数更容易做到这一点。
-
@Lukstorms 在我的测试服务器上 MyPHPAdmin 说
Server version: 10.1.37-MariaDB - mariadb.org binary distribution,在我的生产服务器上 MyPHPAdmin 说Server version: 5.7.25 - MySQL Community Server (GPL)。这能回答你的问题吗? -
确实如此。这意味着您需要一个适用于 5.7 的 SQL。它没有 CTE 和窗口函数。 (但 MariaDB 10 可以)
-
@Strawberry 我在上面提供了一个数据集来解决您的问题。