结合3个MySQL查询进行1次查询

时间:2013-11-27 16:23:48

标签: mysql sql select

我正在尝试在我的网站中构建搜索功能。如果我想搜索照片的标题,文字或标签是否包含“黑色”这个词,我有以下3个查询:

SELECT id 
FROM photos 
WHERE title LIKE '%black%' 
AND status = 'A'

SELECT id 
FROM photos 
WHERE text LIKE '%black%' 
AND status = 'A'

SELECT DISTINCT(photos.id) 
FROM photos, photo_tags, tags 
WHERE tags.tag LIKE '%black%' 
AND photo_tags.keyid = tags.id 
AND photos.id = photo_tags.catid 
AND photos.status = 'A'

是否可以将所有这些组合成1个查询?我知道我可以加入第一个2但是将它与第三个相结合对我来说似乎太复杂了。我尝试加入OR,但我认为我做得不对。

另外我希望它没有重复的结果,所以如果一张照片的标题为“黑色”而标签为“黑色”则只显示一次。

BTW表格看起来像这样,keyid与tag.id有关,catid与photos.id有关。

photos

+----+-----------+-----------------+
| id | title     | text            |
+----+-----------------------------+
|  1 | blue pic  | black and blue  |
|  2 | red pic   | red and green   |
|  3 | green pic | green and white |
|  4 | white pic | white and black |
|  5 | black pic | black and gold  |
+----+-----------+-----------------+

tags

+----+-------+
| id | tag   |
+----+-------+
|  1 | blue  |
|  2 | table |
|  3 | chair |
|  4 | red   |
|  5 | black |
+----+-------+

photo_tags

+-------+-------+
| keyid | catid |
+-------+-------+
|  1    | 1     |
|  2    | 1     |
|  3    | 2     |
|  4    | 2     |
|  5    | 5     |
+-------+-------+    

2 个答案:

答案 0 :(得分:3)

您似乎应该加入表格,然后根据您在两个表格中寻找的文字进行过滤:

SELECT DISTINCT p.id FROM photos p
JOIN photo_tags pt ON pt.cat_id = p.id
JOIN tags t ON pt.key_id = t.id
WHERE (p.title LIKE '%black%' OR t.tag LIKE '%black%') AND p.status = 'A'

答案 1 :(得分:0)

First statement could be your answer. Not sure if you are looking for below output:-

ysql> SELECT DISTINCT(photos.id) FROM photos, photo_tags, tags WHERE tags.tag L
IKE '%black%'AND photos.title LIKE '%black%' AND photo_tags.keyid = tags.id AND
photos.id = photo_tags.catid;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)


mysql> SELECT id
    -> FROM photos
    -> WHERE title LIKE '%black%' ;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.08 sec)

mysql> SELECT id
    -> FROM photos
    -> WHERE text LIKE '%black%';
+------+
| id   |
+------+
|    1 |
|    4 |
|    5 |
+------+
3 rows in set (0.00 sec)

mysql> SELECT DISTINCT(photos.id)
    -> FROM photos, photo_tags, tags
    -> WHERE tags.tag LIKE '%black%'
    -> AND photo_tags.keyid = tags.id
    -> AND photos.id = photo_tags.catid ;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)



mysql> SELECT DISTINCT(photos.id) FROM photos, photo_tags, tags WHERE tags.tag L
IKE '%black%'AND photos.title LIKE '%black%' AND photo_tags.keyid = tags.id AND
photos.id = photo_tags.catid;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)