开发者

Distinct MySQL Results

I have the following SQL query:

SELECT c.comid, d.deid FROM dating_events d JOIN companions c ON d.userid = c.userid WHERE c.userid = 5

Which Outputs somthing like:

-------------
comid | deid
-------------
  2   |   17
  7   |   17
  2   |   18
  7   |   18

But what i want it to output is something like this:

-------------
comid | deid
-------------
  2   |   17
  7   |   18

I tried adding GROUP BY c.comid at the end, it was showing just two results but not quite accurate:

-------------
comid | deid
-------------
  2   |   17
  2   |   18

I also tried adding the DISTINCT keyword after the SELECT but that wasn't doing anything.

Edit - Posting Table Structure:

CREATE TABLE IF NOT EXISTS `companions` (
  `comid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userid开发者_JAVA百科` int(10) NOT NULL,
  `com_name` varchar(60) NOT NULL,
  PRIMARY KEY (`comid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `dating_events` (
  `deid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userid` int(10) unsigned NOT NULL,
  `comid` int(10) unsigned NOT NULL,
  `de_dateadded` datetime NOT NULL,
  PRIMARY KEY (`deid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;


This should be two separate queries:

SELECT DISTINCT c.comid
FROM dating_events d JOIN companions c ON d.userid = c.userid
WHERE c.userid = 5;

and

SELECT DISTINCT d.deid
FROM dating_events d JOIN companions c ON d.userid = c.userid
WHERE c.userid = 5;

The reason for that is that apparently 2/17 and 7/18 are not related, so it does not make sense to put them into tuples. You just have two separate lists of numbers.


You probably want to use SELECT DISTINCT in two separate queries to get the values you are looking for.

Your example output doesn't really make sense because you're arbitrarily grouping the values of comid and deid together. If you want the distinct values for each column you should just do it in 2 queries:

SELECT DISTINCT c.comid
FROM dating_events d 
JOIN companions c ON d.userid = c.userid 
WHERE c.userid = 5

SELECT DISTINCT d.deid 
FROM dating_events d 
JOIN companions c ON d.userid = c.userid 
WHERE c.userid = 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜