Can I get some help with this query. I will explain in details. To make it easier I’ll take an example with HTML tags and attributes.
I have 3 table:
- tbl1 – contains all the HTML tags (
tagId,tagName) - tbl2 – contains all the available attributes that might appear in the
tags (attId,attName) - tbl3 – is a map table for tbl1 and tbl2 (
tagId,attId)
I want to select all the attributes (and related information about the attributes) that belong to the chosen tag (in the example below tag id 4) and the ID of the tag.
Here is an example of what I’d like to get from the query:
attId tagId attName
50 4 The name of the attribute with id 50
89 4 The name of the attribute with id 89
114 4 The name of the attribute with id 114
Below is the query that I’ve made, but I believe there is a better way.
SELECT tbl2.*, tbl3.tagId
FROM tbl2 JOIN tbl3
WHERE tbl3.attId IN (
SELECT tbl3.attId FROM tbl3 where tbl3.tagId=4
)
AND tbl3.attIdd = tbl2.attId
GROUP BY tbl3.attId
Thanks in advance.
Issue 1
You’re doing cross join that you later reduce to an inner join by putting a filter in the
whereclause.This is the old-skool way when using implicit join syntax.
On most SQL-dialects (but not MySQL) this gives an error.
Never do a join without a ON clause.
If you want to do a cross join, use this syntax:
select * from a cross join bIssue 2
The sub select is really not needed, you can just do the test inside a where clause.
Issue 3a
You are doing a group by on
tbl3.ATTid, which in this context is the same as doing a group by ontbl2.attid(because of theON (tbl3.attIdd = tbl2.attId)clause)The latter makes a bit more sense, because you are doing
select tbl2.*, notselect tbl3.*Issue 3b
If attId is not a primary or unique key for tbl2, than the result of the query will be indeterminate.
That means that the query will select a row at random from a list of possible rows with the same
attID. If you don’t want that you’ll have to include ahavingclause that will choose a row based on some criterion.Example