我有表“s_msgs”,他的结构是
id | from | to
------------------
1 | John | Robert
2 | John | Michael
3 | Robert | John
4 | Michael | John
我需要获取每个邮件发件人 - 收件人对,结果必须是
John | Robert
John | Michael
我写了查询,但我认为这不是最优的变体,更可取的是,在表格中会有几百万行,所以有人能说出更优化的查询吗?
这是我的查询
SELECT `from`,`to` FROM s_msgs WHERE id IN(
SELECT id FROM (
SELECT MIN(id) AS id,
CASE
WHEN STRCMP(`to`,`from`) = -1 THEN CONCAT(`to`,`from`)
ELSE CONCAT(`from`,`to`)
END
AS conc
FROM s_msgs
GROUP BY conc
) AS t
)
答案 0 :(得分:1)
怎么样
SELECT DISTINCT `from`, `to`
FROM YOUR_TABLE
UNION
SELECT DISTINCT `to`,`from`
FROm YOUR_TABLE
修改强>
得到一个新的,是救了我的身份证。
看一下这个演示
SELECT *
FROM MY_TABLE f
WHERE NOT EXISTS (
SELECT 1
FROM MY_TABLE t
WHERE f.`from` = t.`to`
AND f.`to` = t.`from`
AND f.id > t.id)