Skip to content
Advertisement

Select unexisting values

I have a database with images which can be tagged.

To tag them I put a value (which represents a color) in a database table called Tagged

Tagged

JavaScript

I also have a table called Tags (the colors)

Tags

JavaScript

In the list with tags are almost 20 tags.

What I have is a page with images so 1 page is imageid 5

if I open the page I want a list of all Tag’s from Tags

If the TagId is in Tagged it must be like

TagId Selected

else just

TagId

How can I do this.

I have the database working to tag images but I can’t get it to ‘see’ if the tag is used.

What I have:

JavaScript

I guess I need a join or what is the best method?

PS I know I should use mysqli but I use mysql for testing now I adjust it later to mysqli

Advertisement

Answer

You can use a LEFT JOIN with a GROUP BY to do one query against the database and get the complete result;

JavaScript

An SQLfiddle to test with.

A short explanation;

I use a LEFT JOIN to select all tags and all possibly matching entries in tagged with ImgId=5. If there is no match, the value of ImgId is NULL, if there is a match, it’s 5. This is a feature of LEFT JOIN.

I then count the number of ImgId‘s per Tag (the COUNT and GROUP BY do that). NULL does not count, so the count becomes 0, while 5 counts and gives the count 1 (remember, we restricted to hits only on a single ImgId, 5).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement