mysql sql distinct加入两个表

时间:2012-05-14 09:42:15

标签: mysql sql join distinct

我有两个mysql表,表event和表eventvenue

我想从场地获得其他活动。

-------------- table event:---------------

id_e
id_event
title
content

-------------- table eventvenue:--------------

id_ev
id_event_ev
id_location_ev

我使用join来从场地获取其他活动:

SELECT * 
FROM eventvenue 
JOIN event ON eventvenue.id_event_ev = event.id_event 
WHERE eventvenue.id_location_ev=1

结果是:

id_ev  id_event_ev  id_location_ev  id_e  id_event  title   content  
-----  -----------  --------------  ----  --------  ------  ------------
1      2            1               2     2         eventA  aaaaaaaaaaaa
2      2            1               2     2         eventA  aaaaaaaaaaaa
1      4            1               4     4         eventB  bbbbbbbbb
1      9            1               9     9         eventC  cccccccc
3      5            1               5     5         event5  555555

输出包含两行,id_event_ev / id_event值为2

如何在每个位置仅显示不同事件ID?像这样:

id_ev  id_event_ev  id_location_ev  id_e  id_event  title   content  
-----  -----------  --------------  ----  --------  ------  ------------
1      2            1               2     2         eventA  aaaaaaaaaaaa
1      4            1               4     4         eventB  bbbbbbbbb
1      9            1               9     9         eventC  cccccccc
3      5            1               5     5         event5  555555

注意:id_ev并不重要。

2 个答案:

答案 0 :(得分:2)

试试这段代码

SELECT * 
FROM eventvenue 
JOIN event ON eventvenue.id_event_ev = event.id_event 
WHERE eventvenue.id_location_ev=1
GROUP BY event.id_event, eventvenue.id_event_ev

答案 1 :(得分:0)

事实上,您只是想忽略id_ev,或者获取它的最低值。

这使你需要

SELECT DISTINCT

-- maybe drop next line
MIN(id_ev) AS id_ev, 
-- maybe drop next line

id_event_ev, id_location_ev, id_e, id_event, title, content 

FROM eventvenue 
INNER JOIN event ON eventvenue.id_event_ev = event.id_event 
WHERE eventvenue.id_location_ev=1

-- Drop next line if you dropped line above
GROUP BY eventvenue.id_ev