如何将两个select语句的结果合并为一个包含两列的表?

时间:2016-09-01 06:58:33

标签: mysql sql

我有两个SELECT语句。两者都给我相同数量的行,并且值彼此相关。

SELECT testtime
FROM testinspection
WHERE sample_id = (
    SELECT id
    FROM sample
    WHERE name = '12_1')

SELECT image
FROM testedsampleimage
WHERE id in (
    SELECT testedsampleimage_id
    FROM testinspection
    WHERE sample_id = (
        SELECT id 
        FROM sample 
        WHERE name = '12_1'))

所以在我的例子中,我有一个特定测试时间的测试图像,我希望将这两个结果放在一个表中,例如这样(例如):

TESTTIME | IMAGE
-------------------
15       | <LONG>
63       | <LONG>
78       | <LONG>
25       | <LONG>
12       | <LONG>

有人知道怎么做吗?

3 个答案:

答案 0 :(得分:1)

SELECT t.testtime,i.image
FROM sample s
   join testinspection t on t.sample_id = s.id
   join testedsampleimage i on t.testedsampleimage_id = i.id
WHERE s.name = '12_1'

答案 1 :(得分:0)

根据idtestedsampleimage_id字段,两个表之间似乎存在1-1关系。在这种情况下,您可以使用简单的JOIN操作:

SELECT testtime, image
FROM testinspection
JOIN testedsampleimage ON id = testedsampleimage_id
WHERE sample_id = (
    SELECT id
    FROM sample
    WHERE name = '12_1')

答案 2 :(得分:0)

您应该使用union来合并两个select语句的结果。

SELECT testtime
FROM testinspection
WHERE sample_id = (
    SELECT id
    FROM sample
    WHERE name = '12_1')

UNION ALL    

SELECT image
FROM testedsampleimage
WHERE id in (
    SELECT testedsampleimage_id
    FROM testinspection
    WHERE sample_id = (
        SELECT id 
        FROM sample 
        WHERE name = '12_1'))

如果您要删除重复值,请仅使用UNION代替UNION ALL