如何从两个查询中只返回一个查询结果

时间:2013-08-05 15:26:26

标签: mysql sql database

我目前拥有的sql查询如下。我尝试了一些联合查询,但它们没有用。

Select file_path
from images
where image_id In (
  Select image_id
  from temp_images
  where object_uid IN (
    Select  object_uid
    from object_table
    where object_status = 2 and object_place like "%some_keyword%"))`


Select object_uid, object_utitle
from object_table
where object_status = 2 and object_place like "%some_keyword%"`

两个查询都可能返回许多行。我想像这样返回file_path和object_uid。

-Image_id | Object_uid | Object_utitle

-img1 | obj1 |标题1

-img2 | obj2 |标题2

-img2 | obj2 |标题3

有没有办法做到这一点?

4 个答案:

答案 0 :(得分:1)

试试这个:

Select a.file_path, b.object_uid, b.object_utitle
from images a, (Select  object_uid, object_utitle
    from object_table
    where object_status = 2 and object_place like "%some_keyword%") b
where image_id In (
  Select image_id
  from temp_images
  where object_uid IN (b.object_uid) )

答案 1 :(得分:0)

Select object_uid, object_utitle from object_table where object_status = 2 and object_place like "%some_keyword%" LIMIT 0,1

它只会选择一个条目,根据您要显示的内容添加ORDER BY DESC/ASC

答案 2 :(得分:0)

您可以加入表格。

   Select i.Image_id , i.file_path , o.object_uid  
   FROM images i
   INNER JOIN temp_images t ON t.image_id = i.image_id
   INNER JOIN object_table o ON o.object_uid = t.object_uid
   WHERE object_status = 2 and object_place like "%some_keyword%"

答案 3 :(得分:0)

使用多个内部联接,您应该尝试类似的东西:

SELECT imgs.image_id, obj.object_uid, obj.object_utitle
    FROM images AS imgs
INNER JOIN temp_images AS tmp_imgs
    ON tmp_imgs.image_id = imgs.image_id
INNER JOIN object_table AS obj
    ON tmp_imgs.object_uid = obj.object_uid
WHERE obj.object_status = 2
    AND obj.object_place LIKE "%some_keyword%"