i will try to explain the problem.
I have this structure:
offers
--------------
id_offer|offer|company
1 | web programmer| Microsoft
2 | web programmer| Microsoft
tags
--------------
id_tags | tags
1 | php
2 | js
3 | asp
offers_has_tags
---------------
offers_id_offer (fk) | tags_id_tags (fk)
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
If i use a system like Stackoverflow, where each title of question is unique, there is no problem with the code below. But if i can have various offers with same title, and with same owner, i can’t do WHERE offers = ?,
So, i need a different approach to select a specific job. Can’t be the title, and can’t be the owner+title, because the same owner can have various offers with same title.
INSERT INTO `offers_has_tags` (
offers_id_offer,
tags_id_tags
)
VALUES (
(SELECT id_offer FROM offers WHERE offer = ?), //here
(SELECT id_tags FROM tags WHERE tags = ?))
How can i select an offer when exists more than one, with same title and same owner ?
Simple answer: there is no way to retrieve exactly one row from table if your where clause is not filtering rows by PK columns.
It is not 100% clear what You are trying to achieve. However, primary key is used to uniquely identify the row. This means that in this case You should use offer_id in where clause (in your insert statement in original question).
I guess that you have some UI in front of this – why don’t your UI send offer_id to data access code instead of offer name?
But, if You want to insert all offers with same name and owner to offer_has_tag, try this (it is T-SQL syntax but as far as I can recall it should work on MySQL also):
Please note that You should use id_tags instead of tag name in your queries. Only use descriptive attributes in filtering the list for end user. Otherwise, use primary key columns.