473,811 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

searching by tags

I have three tables: `photos`, `tags` and `tags_photos`.

The `photos` table contains a unique ID and a bunch of other stuff, the
`tags` table contains a unique ID and a tag name, and the `tags_photos`
contains the photo ID and the tag ID for an association between a tag
and a photo.

In other words, any photo may have many tags and any tag may have many
photos.

This is great for filtering photos based on tag, but I'm now trying to
allow users to search photos on multiple tags. I want users to be able
to enter a list of tags and either search for photos with "all these
tags" or "any of these tags".

I tried the query "SELECT a.* FROM photos AS a, tags_photos AS b WHERE
b.photo=a.id AND b.tag IN ($tags)" where $tags is a comma-separated
list of the tag IDs from the tag names the user entered, but of course
it returns photos multiple times if they have more than one of the
entered tags.

Any ideas?

Jul 23 '05 #1
7 2005
Jasper Bryant-Greene wrote:
I want users to be able
to enter a list of tags and either search for photos with "all these
tags" or "any of these tags".
Using the IN predicate gives you the latter case, but not the former.
I tried the query "SELECT a.* FROM photos AS a, tags_photos AS b WHERE
b.photo=a.id AND b.tag IN ($tags)" where $tags is a comma-separated
list of the tag IDs from the tag names the user entered, but of course
it returns photos multiple times if they have more than one of the
entered tags.


Here are two possible solutions:

1. Using a DISTINCT query modifier:

SELECT DISTINCT a.*
FROM photos AS a, tags_photos AS b
WHERE b.photo = a.id AND b.tag in ($tags)

2. Using a subquery:

SELECT a.*
FROM photos AS a
WHERE a.id IN (
SELECT b.photo
FROM tags_photos AS b
WHERE b.tag IN ($tags))

Regards,
Bill K.
Jul 23 '05 #2
Thanks Bill, the DISTINCT modifier worked perfectly for the "any" case.
Does anyone have any ideas for how to implement the "all" case?

I've been playing around but can't seem to get on the right track.

Jul 23 '05 #3
Jasper Bryant-Greene wrote:
Thanks Bill, the DISTINCT modifier worked perfectly for the "any" case.
Does anyone have any ideas for how to implement the "all" case?


This one is a little more tricky. I don't think you can avoid using a
subquery here.

SELECT DISTINCT a.*
FROM photos AS a, tags_photos AS b
WHERE b.photo = a.id AND b.tag in ( $tags )
AND NOT EXISTS (
SELECT 1
FROM tags AS t LEFT OUTER JOIN tags_photos AS b2
ON (t.id = b2.tag AND b2.photo = a.id)
WHERE t.id IN ( $tags ) AND b2.tag IS NULL)

Regards,
Bill K.
Jul 23 '05 #4
Hi Bill

Thanks for that. I get the following error though:

You have an error in your SQL syntax. Check the manual that corresponds
to your MySQL server version for the right syntax to use near 'EXISTS (
SELECT 1 FROM tags AS t LEFT OUTER JOIN tags_photos AS

Query: SELECT DISTINCT a.* FROM photos AS a, tags_photos AS b WHERE
b.photo=a.id AND b.tag IN (1, 3) AND NOT EXISTS ( SELECT 1 FROM tags AS
t LEFT OUTER JOIN tags_photos AS b2 ON (t.id = b2.tag AND b2.photo =
a.id) WHERE t.id IN (1, 3) AND b2.tag IS NULL )

mysqld Ver 4.0.24 for pc-linux-gnu on i686 (Gentoo Linux
mysql-4.0.24-r1)

Cheers,
Jasper

Jul 23 '05 #5
On 14/06/2005, Bill Karwin wrote:
Jasper Bryant-Greene wrote:
Thanks Bill, the DISTINCT modifier worked perfectly for the "any"
case. Does anyone have any ideas for how to implement the "all"
case?


This one is a little more tricky. I don't think you can avoid using
a subquery here.


Wouldn't this work?

USE test;
DROP TABLE IF EXISTS photos;
CREATE TABLE photos (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(100)
);

INSERT INTO photos (id, name) VALUES
(1, 'My favourite pet'), (2, 'My house'), (3, "Girlfriend 's cat");

DROP TABLE IF EXISTS tags;
CREATE TABLE tags (
tagname VARCHAR(10) NOT NULL,
photo_id INT NOT NULL,
PRIMARY KEY (tagname, photo_id)
);

INSERT INTO tags (tagname, photo_id) VALUES
('pets', 1), ('pets', 3), ('dogs', 1), ('cats', 3), ('buildings', 2);

SELECT
photos.id,
photos.name
FROM photos
JOIN tags ON tags.photo_id = photos.id
WHERE
tags.tagname IN ('pets', 'dogs')
GROUP BY photos.id
HAVING COUNT(*) = 2; # 2 = number of tags
--
felix
Jul 23 '05 #6
Jasper Bryant-Greene wrote:
mysqld Ver 4.0.24


Okay, that explains it. Subqueries were not implemented in MySQL 4.0.x.
They were added in MySQL 4.1. You'll have to use a solution like
Felix's, adapted to your many-to-many table `tags_photos`.

Regards,
Bill K.
Jul 23 '05 #7
Thanks Felix and Bill, I've sorted it out using a solution based on
Felix's but adapted slightly for my many-to-many table.

Once I know whether I'll be using my own server or hosting this
application somewhere, I may well upgrade to MySQL 4.1 anyway.

Jul 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1922
by: SK | last post by:
Is there a way to store HTML into a MySQL TEXT column, yet be able to search over textual content only? For example, if I store the following HTML snippet: <p>A very <em>small</em> paragraph.</p> .... into an TEXT column, I would like to be able to search in the text "A very small paragraph." only, meaning the search would find "small" (even if it's enclosed in <em> tags and
4
1748
by: ash | last post by:
I want search phrase in html file and mark (like Google when I click on "cached") it (phrase). Does somebody know any class, that can help me? Maybe somebody know how could I make this? thanks
0
1186
by: Tom | last post by:
Hi, Does anyone know if MS Indexing Service searches meta tags. I have a requirement to search meta tags. cheers. John.
7
2324
by: Nash Kabbara | last post by:
Hi all, I just finished writing a log reader that reads xml logs (about 1 to 2 MB large). At the command line you can specify the file name, the name of the element and it's value like so: logreader log.txt MyElement myvalue In retrospect, I've noticed that it takes a long time to process. The time is spent on comparing the value of all tags named MyElement to myvalue. Namely:     
14
5381
by: Ludwig77 | last post by:
I read that there are some tags that can be entered in a web page's meta tags in order to prevent web bot searching and indexing of the web page for search engines. What is the tagging that I would need to use?
2
1500
by: anand | last post by:
Hello Group , I am making a search programe in which i have to make a search in an HTML document .Now i am having entire html code in a field of table where i search.Now my issue is that i want to avoid searching of html tags like <td>, <tr> etc, i.e. when user searches these tags i wand to display no results , is there any way i can skip these html specific tags programatically. Thanks
2
2081
by: neilio2j | last post by:
hi, can anyone tell me how to search a given directory using C++? so far i have been successful in searching a file named, for tags"h:\\tags.cpp", whereas i would like to search for all files in the entire h: directory. this is the code i have used for searching the file named, "h:\\tags.cpp", /*char filename; cout<<"Please enter the filename";
0
911
by: skumar2008 | last post by:
This may not be the right forum for this question so my appologies in advance. But I turn to this group as a last resort... To give an example of my problem/question: Suppose I have a database that stores photos and "tags" (search keywords) associated with each photo. Of course the binary of the photo is not in the database itself. I want to be able to support searches for one of more key words. This database has a potential of hundreds...
1
2787
by: alamodgal | last post by:
hiiiiiii I have a problem in highlighting searching keyword.Actually im using this function for searching Public Function HighLight(ByVal Keyword As String, ByVal ContentFor As String) Dim objHighLight As New highlight(Keyword, "<span class='searchKeyword'>{keyword}</span>") ContentFor = objHighLight.process(ContentFor, False, False) Return ContentFor 'Dim RegExp As Regex = New Regex(Keyword.Replace(" ", "|").Trim(),...
0
9731
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7671
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5556
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4342
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3871
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.