Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Select on two values one column

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?

like image 977
Tim Hanssen Avatar asked Jan 07 '13 12:01

Tim Hanssen


People also ask

How do I select multiple values from the same column in MySQL?

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);

How do I select multiple values from one table in MySQL?

To select multiple values, you can use where clause with OR and IN operator.

How do I select between values in MySQL?

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.


2 Answers

Try this:

SELECT *  
FROM tablename 
WHERE keywordId IN (1, 12) 
GROUP BY articleId 
HAVING COUNT(*) = 2; 

Check the SQL FIDDLE DEMO

like image 68
Saharsh Shah Avatar answered Oct 26 '22 13:10

Saharsh Shah


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
);;
like image 32
Mahmoud Gamal Avatar answered Oct 26 '22 13:10

Mahmoud Gamal