I have three TABLES in MySQL:
items
, category
and intermediate
(to allow 'many-to-many' relationships).
TABLE category: TABLE items:
id_category theme id_items part
1 dog 1 tomato
2 fruit 2 rottweiler
3 bird 3 blackbird
4 veg 4 apple
TABLE intermediate
:
id_intermediate id_category id_items
1 1 2
2 2 4
3 3 3
4 4 1
There are thousands of entries in each of the tables category
and items
but 'only' hundreds in the 'relationship' table - intermediate
.
now, what I want to do is to query for a certain value, a variable using LIKE '%$var'
to check for similar results (spelled word) but only on the COLUMN part
in the TABLE items
, that have associations or that exist in the TABLE intermediate
.
I know how to do the query on the TABLE items
(use PHP):
$query = "SELECT * FROM items WHERE part LIKE '%$var%' LIMIT 10";
but as I mentioned, I need only those that have association with the other TABLE category
.
I've tried many things, includeding a nested query like:
$query = "SELECT * FROM
(SELECT items.part, items.id_items, id_intermediate, id_items
FROM items JOIN intermediate
WHERE inter.id_items IS NOT NULL)
WHERE items.part LIKE '%$var%'";
but I got this error:"Invalid query: Every derived table must have its own alias", which I don't really understand.
In any case, does any one here know how to solve my problem?
I couldn't find such a question in this forum.
UPDATE (solution): scaisEdge provided the solution.
$query =
SELECT items.part, items.id_items, inter.id_intermediate, inter.id_items
FROM items
JOIN intermediate on inter.id_items
JOIN category on inter.id_category = category.id AND inter.id_items = items.id_items
WHERE items.part LIKE concat ('%', '$var' , '%') ";
I believe this isn't a duplicate because the other proposals refer to the ALIAS error, which was part of my false attempt. But even with solving the alias error, it had to go through a different approach.