合并来自2个不同SELECT请求的结果(逻辑AND)

时间:2013-08-19 13:52:29

标签: mysql

我在数据库中有2个表:

$ SELECT * from image
+----------+------+-----+
| image_id | good | bad |
+----------+------+-----+
|        1 |    2 |   0 |
|        2 |    1 |   0 |
|        3 |    0 |   0 |
|        4 |    1 |   0 |

$ SELECT * from image_tag_map
+----------+--------+-------+
| image_id | tag_id | score |
+----------+--------+-------+
|        1 |      1 |   255 |
|        2 |      1 |   255 |
|        3 |      1 |   255 |
|        4 |      2 |   255 |

SELECT * FROM image_tag_map WHERE tag_id=$tagID and score>=5;
result : 1, 2, 3 (image_id)

SELECT * FROM image WHERE good!=0 ORDER BY good DESC;
result : 1, 2, 4 (image_id)

我希望得到1,2。 (所以这两个命令之间的混合) 两个地方都有“image_id”。 我尝试过INNER JOIN等,但是找不到合适的东西......

7 个答案:

答案 0 :(得分:0)

除了使用JOIN之外,您还可以使用EXISTS

SELECT  a.*
FROM    image a
WHERE   a.good <> 0 AND
        EXISTS
        (
            SELECT  1
            FROM    image_tag_map b
            WHERE   a.image_id = b.image_id AND
                    tag_id = $tagID AND 
                    score >= 5
        )
ORDER   BY a.good DESC

答案 1 :(得分:0)

JOIN两个表:

SELECT  *
FROM image AS i
INNER JOIN image_tag_map AS m ON i.image_id = m.image_id
WHERE m.tag_id=$tagID and m.score>=5
  AND i.good != 0
ORDER BY i.good DESC;

答案 2 :(得分:0)

JOIN应该有效

SELECT * FROM image_tag_map itm 
JOIN image i ON i.image_id = itm.image_id 
WHERE itm.tag_id=$tagID 
AND itm.score>=5
AND i.good!=0
GROUP BY i.image_id

答案 3 :(得分:0)

你试过这个吗?

SELECT distinct itm.image_id
FROM image_tag_map itm join
     image i
     on itm.image_id = i.image_id
WHERE item.tag_id=$tagID and item.score>=5 and i.good <> 0;

答案 4 :(得分:0)

尝试

SELECT m.* FROM image_tag_map m 
  inner join image i on m.image_id = i.id 
   WHERE tag_id=$tagID and score>=5 and i.good !=0

答案 5 :(得分:0)

你只需要身份证吗?有几种方法......

SELECT image_id FROM image
WHERE good <> 0
AND image_id IN (
  SELECT image_id FROM image_tag_map
  WHERE tag_id = ? AND score >= 5
)

SELECT image_id FROM image
WHERE good <> 0
AND EXISTS (
  SELECT image_id FROM image_tag_map
  WHERE image_tag_map.image_id = image.image_id
  AND tag_id = ? AND score >= 5
)

使用INNER JOIN也应该有效:

SELECT image_id FROM image i
INNER JOIN image_tag_map itm
ON i.image_id = itm.image_id
WHERE i.good <> 0
AND itm.score >= 5
AND itm.tag_id = ?

答案 6 :(得分:0)

怎么样?

select image_id from image where good <> 0 and image_id in 
    (select image_id from FROM image_tag_map WHERE tag_id= ? and score>=5)
    order by good desc