我有这个查询,目前正在返回两个结果
SELECT h1.*
FROM profile AS h1
INNER JOIN profile h2
ON (h1.memid = h2.ph_memid
AND h1.ph_memid = h2.memid)
WHERE h1.event_id = '5496'
但我试图得到的结果只有1或2 ......条件是329和399必须在两个具有相同事件ID的列中 意味着
memid ph_memid
329 399
399 329
其中事件id的结果必须相同。这里是1。 表模式是在 http://sqlfiddle.com/#!2/9d4f1/1 请帮忙。
答案 0 :(得分:1)
这或许你需要ie group by和count()
SELECT h1.*,count(*) as `tot`
FROM profile AS h1
INNER JOIN profile h2
ON (h1.memid = h2.ph_memid
AND h1.ph_memid = h2.memid)
WHERE h1.event_id = '5496'
group by `h1`.`event_id`
如果你想减少更多,即相对于dt(日期)的数量,你需要添加第二组by
SELECT h1.*,count(*) as `tot`
FROM profile AS h1
INNER JOIN profile h2
ON (h1.memid = h2.ph_memid
AND h1.ph_memid = h2.memid)
WHERE h1.event_id = '5496'
group by `h1`.`event_id` , `h1`.`dt`
答案 1 :(得分:1)
元组(329,399)和(399,329)相同,因为它们具有相同的值,即它们的较低值(329)相等并且它们的较高值(399)相等。因此,在较低和较高的值上使用不同的选择来获得一个记录而不是两个:
SELECT DISTINCT least(h1.memid, h1.ph_memid), greatest(h1.memid, h1.ph_memid)
FROM profile h1
INNER JOIN profile h2 ON h1.memid = h2.ph_memid AND h1.ph_memid = h2.memid
WHERE h1.event_id = '5496';
顺便说一下,你不要将h2限制为event_id ='5496'。这是故意的吗?
这是SQL小提琴:http://sqlfiddle.com/#!2/9d4f1/25
编辑:如果它只是计数,你感兴趣,使用COUNT(DISTINCT ...):
SELECT COUNT(DISTINCT least(h1.memid, h1.ph_memid), greatest(h1.memid, h1.ph_memid))
FROM profile h1
INNER JOIN profile h2 ON h1.memid = h2.ph_memid AND h1.ph_memid = h2.memid
WHERE h1.event_id = '5496';