Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Query returns empty result, unexpected result

Tags:

sql

mysql

Can anyone explain why this query returns an empty result.

SELECT *
FROM (`bookmarks`)
JOIN `tags` ON `tags`.`bookmark_id` = `bookmarks`.`id`
WHERE `tag` = 'clean'
AND `tag` = 'simple'

In my bookmarks table, I have a bookmark with an id of 70 and in my tags table i have two tags 'clean' and 'simple' both that have the column bookmark_id as 70. I would of thought a result would have been returned?

How can I remedy this so that I have the bookmark returned when it has a tag of 'clean' and 'simple'?

Thanks all for any explanation and solution to this.

Update

My tag table holds many tags. A bookmark can have many tags. id in the bookmarks table and the bookmark_id in the tags table are linked.

like image 905
Abs Avatar asked Jul 08 '26 11:07

Abs


2 Answers

It's unlikely that there's a row whose tag equals both 'clean' and 'simple' :)

So try replacing AND with OR:

WHERE `tag` = 'clean'
OR `tag` = 'simple'

If you intend to retrieve only bookmarks with both tags, consider a double exists clause:

SELECT *
FROM bookmarks b
WHERE EXISTS (
    SELECT *
    FROM tags t
    WHERE t.tag = 'simple'
    AND t.bookmark_id = b.id
) AND EXISTS (
    SELECT *
    FROM tags t
    WHERE t.tag = 'clean'
    AND t.bookmark_id = b.id
)

It's also possible to check using a having statement:

SELECT    b.id
FROM      bookmarks b
JOIN      tags t
ON        t.bookmark_id = b.id
          AND t.tag in ('clean','simple')
GROUP BY  b.id
HAVING    COUNT(distinct t.tag) = 2

The count will ensure both tags are found.

like image 163
Andomar Avatar answered Jul 10 '26 01:07

Andomar


You get no rows because your where clause is impossible to satisfy.

To get bookmarks that have both a tag 'clean' and a tag 'simple' you need to join with the tags table twice. Try doing it like this:

SELECT bookmarks.*
FROM bookmarks
JOIN tags AS T1 ON T1.bookmark_id = bookmarks.id AND T1.tag = 'clean'
JOIN tags AS T2 ON T2.bookmark_id = bookmarks.id AND T2.tag = 'simple'
like image 33
Mark Byers Avatar answered Jul 10 '26 03:07

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!