views:

65

answers:

3

I have three tables namely 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

how get test_id value with q_id = 2 from these three tables without repeating data ?

that is 25, 27, 34

A: 
SELECT test_id
FROM (
    SELECT * FROM test1 UNION
    SELECT * FROM test2 UNION
    SELECT * FROM test3
) tests
WHERE q_id = 2
just somebody
SELECT DISTINCT test_id ...
klausbyskov
This query would cause an unnecessary amount of overhead if you are dealing with larger tables. See solution below.
cballou
+2  A: 

If you really can't get rid of two of the three structural identical tables take a look at the UNION operator. The default behaviour is UNION DISTINCT which removes duplicates from the results.

  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
VolkerK
this from the mysql manual (and indeed, it's the behavior prescribed by the SQL standard):The default behavior for UNION is that duplicate rows are removed from the result. The optional DISTINCT keyword has no effect other than the default because it also specifies duplicate-row removal.
just somebody
Yes, it's the default behaviour (as already mentioned in the answer) and it also does no harm to write it explicitly into the query (for clarity).
VolkerK
+1  A: 

@just somebody - Your query is doing 3 select * which might be intensive, it is best to limit all three to avoid an unnecessary number of rows:

    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

The above query was modified to reflect which table each q_id came from.

cballou
What's the reason for wrapping the thing in a sub-query?
VolkerK
isn't the database smart enough to see that it's only test_id that's needed? i thought mysql has grown up a bit since the 3.22 days... sigh.
just somebody
@VolkerK - good point, I had simply pasted and modified @just somebody's code to show the optimization.
cballou