表1
- | a | b | C | d | e |
- |----+----+----+----+----|
- | 1 | 2 | 3 | 2 | 9 |
- | 2 | 3 | 2 | 3 | 5 |
- | 3 | 8 | 4 | 4 | 2 |
- | 4 | 9 | 8 | 5 | 3 |
- | 5 | 1 | 9 | 7 | 1 |
- | 6 | 12 | 10 | 9 | 10 |
表2
- | a2 | b2 | C2 | d2 | e2 |
- |----+----+----+----+----|
- | 1 | 2 | 3 | 2 | 9 |
- | 2 | 3 | 2 | 3 | 5 |
- | 3 | 8 | 4 | 4 | 2 |
- | 4 | 9 | 8 | 5 | 3 |
- | 5 | 1 | 9 | 7 | 1 |
- | 6 | 12 | 10 | 9 | 10 |
我想要的结果:
2,3
因为2和3在这两个表的所有列中都很常见。
我试过了:
SELECT DISTINCT c1.a FROM `table1` c1
JOIN `table1` c2 ON ( c1.a = c2.b )
JOIN `table1` c3 ON ( c2.b = c3.c )
JOIN `table1` c4 ON ( c3.c = c4.d )
JOIN `table1` c5 ON ( c4.d = c5.e )
LIMIT 0 , 10
它适用于table1,但如何加入更多表。
答案 0 :(得分:1)
完全一样:
SELECT DISTINCT c1.a FROM `t1` c1
JOIN `t1` c2 ON ( c1.a = c2.b )
JOIN `t1` c3 ON ( c2.b = c3.c )
JOIN `t1` c4 ON ( c3.c = c4.d )
JOIN `t2` c5 ON ( c4.d = c5.a )
JOIN `t2` c6 ON ( c5.b = c6.c )
JOIN `t2` c7 ON ( c6.c = c7.d )
LIMIT 0 , 10
检查这个小提琴:http://sqlfiddle.com/#!2/46ade/6
答案 1 :(得分:0)
嗯,你可以从这个fiddle开始,共10行。
您将其计算在哪里等于您要比较的行数 您的示例有table1 6行,table2 6行。 例如12行是......
SELECT
a.value,
COUNT(a.value) as count
FROM
(
SELECT a AS value
FROM table1
UNION ALL
SELECT b AS value
FROM table1
UNION ALL
SELECT C AS value
FROM table1
UNION ALL
SELECT d AS value
FROM table1
UNION ALL
SELECT e AS value
FROM table1
UNION ALL
SELECT a2 AS value
FROM table2
UNION ALL
SELECT b2 AS value
FROM table2
UNION ALL
SELECT C2 AS value
FROM table2
UNION ALL
SELECT d2 AS value
FROM table2
UNION ALL
SELECT e2 AS value
FROM table2
) a
GROUP BY value
HAVING count >= 12
ORDER BY count DESC
要在行数上更加动态,您也可以尝试:
HAVING count >= ((SELECT COUNT(*) as t1 FROM table1) + (SELECT COUNT(*) as t2 FROM table2))
<强>更新
与您的方法类似的是:http://sqlfiddle.com/#!2/56d52/4
SELECT t.value, COUNT(t.value) as count
FROM
(
SELECT DISTINCT c1.a AS value FROM `table1` c1
JOIN `table1` c2 ON ( c1.a = c2.b )
JOIN `table1` c3 ON ( c2.b = c3.c )
JOIN `table1` c4 ON ( c3.c = c4.d )
JOIN `table1` c5 ON ( c4.d = c5.e )
UNION ALL
SELECT DISTINCT c1.a2 AS value FROM `table2` c1
JOIN `table2` c2 ON ( c1.a2 = c2.b2 )
JOIN `table2` c3 ON ( c2.b2 = c3.C2 )
JOIN `table2` c4 ON ( c3.C2 = c4.d2 )
JOIN `table2` c5 ON ( c4.d2 = c5.e2 )
) t
GROUP BY t.value
HAVING count = 2