我试图合并两个没有重复行的表
表1-modx_网站内容

|id|pagetitle|introtext|pub_date|
---------------------------------
|3635| name1 |texttextt|17.02.2015
|3636| name1 |texttextt|18.02.2015

表2-modx_site_tmplvar_contentvalues
|contentid|tmplvarid|value|
---------------------------
|   3635  |    1    |value1
|   3635  |    1    |value2
|   3636  |    1    |value3

我试着把所有的
|id|title|introtext|publishdate|photo|
--------------------------------------
|3635|name1|texttextt|17.02.2015|value1, value2
|3636|name1|texttextt|18.02.2015|value3

但当前结果显示dublicate行id 3535
|id|title|introtext|publishdate|photo|
--------------------------------------
|3635|name1|texttextt|17.02.2015|value1
|3635|name1|texttextt|17.02.2015|value2
|3636|name1|texttextt|18.02.2015|value3

我当前的sql resest是
SELECT
    modx_site_content.id,
    pagetitle as 'title',
    introtext,
    pub_date as 'publishdate',
    modx_site_tmplvar_contentvalues.value as 'photo'

FROM `modx_site_content`,
    `modx_site_tmplvar_contentvalues`

WHERE parent IN (1153,3271)
    AND pub_date>0
    AND `contentid`= modx_site_content.id
    AND `tmplvarid` IN (10, 15, 19)

Order by `pub_date` DESC LIMIT 20

最佳答案

解决你眼前问题的办法是group bygroup_concat()

SELECT c.id, c.pagetitle as title, c.introtext, c.pub_date as publishdate,
       group_concat(cv.value) as sphotos
FROM `modx_site_content` c JOIN
     `modx_site_tmplvar_contentvalues` cv
     ON cv.`contentid`= c.id
WHERE c.parent IN (1153, 3271) AND c.pub_date > 0 AND
      `tmplvarid` IN (10, 15, 19)
GROUP BY c.id, c.pagetitle, c.introtext, c.pub_date
Order by c.`pub_date` DESC
LIMIT 20;

我还建议:
使用显式join语法。
from子句中定义表别名。
对列引用使用表别名。
不要使用单引号来定义列别名。你不需要一个转义符,所以不要同时使用一个。

关于mysql - SQL Join 2表没有重复的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28587161/

10-16 11:31