我对如此模糊的标题表示歉意。
我有一个MySQL表,其中包含Wordpress博客文章。该表包含帖子及其翻译,例如:
----------------------------------------------------
|post_name|post_type|post_status|post_date |
----------------------------------------------------
|My post | post | publish |2019-05-18 05:00:20 |
----------------------------------------------------
| Mi post | post | publish |2019-05-18 05:00:20 |
----------------------------------------------------
每个帖子和每个翻译都是表中独立的帖子条目。我正在尝试整理一条SQL语句,该语句将为我提供帖子及其翻译名称的列表。翻译之间唯一的共同点是事实帖子的日期完全相同。
到目前为止,我写道:
SELECT t1.post_name, t2.post_name, t1.post_date
FROM `posts` t1 LEFT JOIN `posts` t2 ON t1.post_date = t2.post_date
WHERE t1.post_status='publish' and
t1.post_type='post' and
t1.post_name<>t2.post_name
ORDER BY t1.post_date DESC
-----------------------------------------
|post_name|post_name| post_date |
-----------------------------------------
|My post | Mi post | 2019-05-18 05:00:20 |
-----------------------------------------
| Mi post | My post | 2019-05-18 05:00:20 |
-----------------------------------------
如您所见,我两次获得条目(这很合逻辑)。那么,如何消除重复的条目?
谢谢
答案 0 :(得分:1)
您使用t1.post_name <> t2.post_name
而不是t1.post_name < t2.post_name
来获得一对。但是,那不一定会给您一侧的一种语言,而另一侧的另一种语言。您需要采取一些措施来检测获得该语言的语言。
还要注意,对t1
和t2
的列进行比较后,无声地将LEFT JOIN
更改为INNER JOIN
,因此更明确地将其写为这样。< / p>
SELECT t1.post_name,
t2.post_name,
t1.post_date
FROM `posts` t1
INNER JOIN `posts` t2
ON t1.post_date = t2.post_date
WHERE t1.post_status = 'publish'
AND t1.post_type = 'post'
AND t1.post_name < t2.post_name
ORDER BY t1.post_date DESC;
答案 1 :(得分:1)
如果我们假设第一个帖子(按id)是原始帖子,并且 all 都有翻译,那么您可以这样做:
SELECT p.post_name, pt.post_name, p.post_date
FROM posts p JOIN
posts pt
ON pt.post_date = t2.post_date AND
pt.id > p.id
WHERE p.post_status = 'publish' and
p.post_type = 'post' and
pt.post_status = 'publish' and
pt.post_type = 'post'
ORDER BY p.post_date DESC
答案 2 :(得分:0)
我有个建议,您可以在帖子中添加类别,例如每种语言的英语,法语。这样,您可以轻松地对帖子进行分组。我添加了DATE_FORMAT,以使每个帖子的日期与另一个帖子的日期完全匹配(如果日期和时间完全相同,则可以忽略这一点)。我添加了两个以上的左联接,以检查类别(语言)是否不同。这样查询将给出正确的结果。然后查询将变为
SELECT t1.post_name, t2.post_name, t1.post_date, tr1.term_taxonomy_id, tr2.term_taxonomy_id
FROM `posts` t1 LEFT JOIN `posts` t2 ON date_format(t1.post_date, "%Y-%m-%d") = date_format(t2.post_date, "%Y-%m-%d") left join `term_relationships` tr1 on t1.ID=tr1.object_id left join `term_relationships` tr2 on t2.ID=tr2.object_id
WHERE t1.post_status='publish' and
t1.post_type='post' and
t2.post_type='post' AND
t2.post_status='publish' AND
t1.post_name<>t2.post_name
ORDER BY t1.post_date DESC