我有三个表,即test1,test2,test3
test1 data
===========
id test_id q_id
1 25 2
2 27 2
test2 data
===========
id test_id q_id
1 25 2
2 34 2
test3 data
===========
id test_id q_id
1 34 2
如何在不重复数据的情况下从这三个表中获取test_id
q_id = 2
值?
即25,27,34
答案 0 :(得分:2)
如果你真的无法摆脱三个结构相同的表中的两个,请看一下UNION运算符。默认行为是UNION DISTINCT ,它会从结果中删除重复项。
SELECT test_id FROM test1 WHERE q_id=2
UNION DISTINCT
SELECT test_id FROM test2 WHERE q_id=2
UNION DISTINCT
SELECT test_id FROM test3 WHERE q_id=2
答案 1 :(得分:1)
@just somebody - 你的查询正在做3选择*可能是密集的,最好限制所有三个以避免不必要的行数:
SELECT test_id, 'test1' AS tableName FROM test1 WHERE q_id = 2
UNION
SELECT test_id, 'test2' AS tableName FROM test2 WHERE q_id = 2
UNION
SELECT test_id, 'test3' AS tableName FROM test3 WHERE q_id = 2
修改了上述查询以反映每个q_id来自哪个表。
答案 2 :(得分:0)
SELECT test_id
FROM (
SELECT * FROM test1 UNION
SELECT * FROM test2 UNION
SELECT * FROM test3
) tests
WHERE q_id = 2