简体   繁体   中英

Why doesn't the WHERE work in this sql query

I'm writing a SQL query that needs to only show the results where the 'titel' is the same as 'Baklava', but it doesn't return any rows. When I try to use the query without the WHERE , is shows all the results, but I need the WHERE clause to work.

Here is the query I'm trying to use:

SELECT *, tags.titel AS tags
FROM posts_tags
INNER JOIN tags ON posts_tags.post_id = tags.id
INNER JOIN posts ON posts.id = tags.id 
WHERE tags.titel = 'Baklava';

import.sql:

CREATE DATABASE foodblog;

USE foodblog;

CREATE TABLE `auteurs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `auteur` varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
);

INSERT INTO `auteurs` (`id`, `auteur`) VALUES
(1, 'Mounir Toub'),
(2, 'Miljuschka'),
(3, 'Wim Ballieu');

CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titel` varchar(255) DEFAULT NULL,
  `datum` datetime DEFAULT current_timestamp(),
  `img_url` varchar(255) DEFAULT NULL,
  `inhoud` text DEFAULT NULL,
  `auteur_id` int(11) DEFAULT NULL,
  `likes` int(11) DEFAULT NULL,
  PRIMARY KEY (id)
);

INSERT INTO `posts` (`id`, `titel`, `datum`, `img_url`, `inhoud`, `auteur_id`, `likes`) VALUES
(1, 'Pindakaas', '2020-06-18 13:25:00', 'https://i.ibb.co/C0Lb7R1/pindakaas.jpg', 'Verwarm de oven voor op 180 °C. Verdeel de pinda’s over een met bakpapier beklede bakplaat en rooster in ca. 8 min. lichtbruin. Schep regelmatig om. Maal de warme pinda’s in de keukenmachine in 4 min. tot een grove, dikke pindakaas. Schep de rand van de kom regelmatig schoon met een spatel. Voeg het zout, de olie en honing toe en maal nog 1 min. tot een gladde pindakaas. Schep in een pot en sluit af.\r\n        variatietip: Houd je van pindakaas met een smaakje? Voeg dan na de honing 1 el sambal badjak, 1 tl gemalen kaneel of 1 el fijngehakte pure chocolade toe. bewaartip: Je kunt de pindakaas 3 weken in de koelkast bewaren.', 1, 13),
(2, 'Baklava', '2020-03-11 10:28:00', 'https://i.ibb.co/ZWVRdPT/baklava.jpg', 'Voorbereiding\r\n\r\n    Verwarm de oven voor op 190 °C. Vet de bakvorm in met roomboter.\r\n    Smelt de roomboter in een pannetje. Snijd het baklavadeeg op dezelfde breedte als de bakvorm en bewaar het in een schone droge keukendoek om uitdrogen te voorkomen. Verwarm in een pan 300 gr honing met 20 ml oranjebloesemwater en houd dit mengsel warm. Roer in een mengkom de gezouten roomboter, 500 g gemalen walnoten, de rest van de honing en het oranjebloesemwater en de kaneel door elkaar. Verdeel het mengsel in zeven gelijke porties (van circa 90 g).\r\n\r\n    Bereiding\r\n    Bestrijk een vel baklavadeeg met gesmolten roomboter. Leg er een tweede vel op en bestrijk dat ook. Neem één portie van het walnotenmengsel en verdeel dat onderaan over het baklavadeeg. Rol op tot een staaf, leg deze in de bakvorm en bestrijk met gesmolten roomboter. Maak de rest van de staven op dezelfde manier.\r\n    Snijd elke staaf met een scherp mes meteen in zessen. Bak de baklava in circa 25 minuten goudbruin en krokant in de oven.\r\n    Neem de bakvorm uit de oven en verdeel de warme honing over de baklava. Garneer meteen met de rest van de fijngemalen walnoten. Laat de baklava minimaal 3 uur afkoelen voordat je ervan gaat genieten.', 3, 7);

CREATE TABLE `posts_tags` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) DEFAULT NULL,
  `tag_id` int(11) DEFAULT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE `tags` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titel` varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
);

INSERT INTO tags (id, titel)
VALUES (1, 'Baklava');

INSERT INTO posts_tags (id, post_id, tag_id)
VALUES (1, 2, 1);

ALTER TABLE `posts`
  ADD KEY `auteur_id` (`auteur_id`);

--
-- Indexen voor tabel `posts_tags`
--
ALTER TABLE `posts_tags`
  ADD KEY `post_id` (`post_id`),
  ADD KEY `tag_id` (`tag_id`);

ALTER TABLE `posts`
  ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`auteur_id`) REFERENCES `auteurs` (`id`);

ALTER TABLE `posts_tags`
  ADD CONSTRAINT `posts_tags_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`),
  ADD CONSTRAINT `posts_tags_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`);
COMMIT;

You have not inserted any rows in to the posts_tags table, so there's no link between the posts and the tags .

Try:

INSERT INTO `posts_tags` (`post_id`, `tag_id`) VALUES (2,1);

Your query has a mistake as well:

SELECT *, tags.titel AS tags
FROM posts_tags
INNER JOIN tags ON posts_tags.post_id = tags.id <<< ????
INNER JOIN posts ON posts.id = tags.id <<< ???
WHERE tags.titel = 'Baklava';

Should be

SELECT *, tags.titel AS tags
FROM posts_tags
INNER JOIN tags ON posts_tags.tag_id = tags.id
INNER JOIN posts ON posts_tags.post_id = posts.id 
WHERE tags.titel = 'Baklava';

Then run your query again.

I would also suggest you change the posts_tags table, removing the id field as it's not needed, and without a unique constraint on the other fields you can end up with a tag added multiple times to the same post. Create a composite primary key instead:

CREATE TABLE `posts_tags` (
  `post_id` int(11) DEFAULT NULL,
  `tag_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`post_id`, `tag_id`)
);

You have three issues in your statement. The first is that your posts_data table is empty, so an INNER JOIN produces an empty result set.

The second is an error in the INSERT statement that fills the tags table, so this is also empty.

And the third issue seems to be that the columns you join on do not seem to be logically correct.

Try adding the following to your import.sql :

INSERT INTO posts_tags VALUES (1, 2, 1)

and fixing the other INSERT statement:

INSERT INTO tags VALUES (1, 'Baklava')

The data now correctly indicates post 2 is related to tag 1 .

Then fix your ON clauses so that they make sense:

SELECT *, tags.titel AS tags
FROM posts_tags
INNER JOIN tags ON posts_tags.tag_id = tags.id
INNER JOIN posts ON posts.id = posts_tags.post_id 
WHERE tags.titel = 'Baklava'

This produces your desired result.

See this db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM