我有以下SQL查询:
SELECT c.comid, d.deid FROM dating_events d JOIN companions c ON d.userid = c.userid WHERE c.userid = 5
哪个输出类似:
-------------
comid | deid
-------------
2 | 17
7 | 17
2 | 18
7 | 18
但是我希望它输出的是这样的:
-------------
comid | deid
-------------
2 | 17
7 | 18
我最后尝试添加GROUP BY c.comid,它只显示了两个结果但不太准确:
-------------
comid | deid
-------------
2 | 17
2 | 18
我也尝试在SELECT之后添加DISTINCT关键字但是没有做任何事情。
编辑 - 过帐表格结构:
CREATE TABLE IF NOT EXISTS `companions` (
`comid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userid` 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;
答案 0 :(得分:1)
这应该是两个单独的查询:
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;
原因是显然2/17和7/18没有关联,因此将它们放入元组是没有意义的。你只有两个单独的数字列表。
答案 1 :(得分:0)
您可能希望在两个单独的查询中使用SELECT DISTINCT
来获取您要查找的值。
您的示例输出实际上没有意义,因为您可以将comid和deid的值任意分组在一起。如果您想要每列的不同值,您应该只在2个查询中执行:
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