I need to select a row from my mysql table.
In the table there are two rows with one equal value.
TABLE
-----
articleId
keywordId
Now I need to select an article, that has keyword Id = 1, as well as keyword Id = 12.
Every link to a keyword has its own record.
How can I do one select query to know, if there is an article, that matches the two keywords?
Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);
To select multiple values, you can use where clause with OR and IN operator.
BETWEEN is a logical operator in SQL used to select a range of values from the database table. Using the between the query, we can also check whether a value is in the provided range or not. BETWEEN is generally used with SELECT statements and with INSERT, DELETE, and UPDATE queries.
Try this:
SELECT *
FROM tablename
WHERE keywordId IN (1, 12)
GROUP BY articleId
HAVING COUNT(*) = 2;
Check the SQL FIDDLE DEMO
This is called Relation Division. Here is one way to do so:
SELECT *
FROM tablename
WHERE articleId IN
(
SELECT articleId
FROM tablename
WHERE KeywordId IN (1, 2)
GROUP BY articleId
HAVING COUNT(KeywordId ) = 2
);;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With