Reputation: 619
I have 2 tables, article
and image
.
In order to extract all articles of a particular user, I need to:
query all the articles
SELECT * FROM article WHERE userid=100;
then loop through these articles, and extract their images with:
SELECT * FROM image WHERE articleid = currentArticleId;
How can I achieve the same thing with just a single query?
Upvotes: 3
Views: 25450
Reputation: 4063
You could use a join or a subquery.
The subquery (The second query contained in brackets) will be executed and the ID(s) that are returned will be used to identify which rows from the initial query to grab. So if you imagine the subquery returns (1, 2, 3), the initial query will be looking for rows WHERE articleid
is IN
that list.
SELECT * FROM image WHERE articleid IN (SELECT id FROM article WHERE userid=100);
Join:
Here you are telling MySQL that the articleid
in image
is related to the id
column in the article
table. Then you can just pull columns from either table. This is a watered down explanation so I recommend you read the link. There are various types of JOIN
that will result in different results, so you should read about LEFT
, RIGHT
, OUTER
and INNER
joins to make sure the resultset fits your needs. In this case, JOIN
is equivalent to an INNER
join.
SELECT
image.col1,
image.col2,
image.colX,
article.col1,
article.col2,
article.colX
FROM image
JOIN article ON article.id = image.articleid;
Upvotes: 11
Reputation: 6180
You can use @Doctus 's answer, but when joining the table you need to take care of proper joining
.
In your case, some user might not have images.
--//This will also get the articles without any images
SELECT article.* , image.*
FROM article
LEFT OUTER JOIN image
ON article.articleid = image.articleid
WHERE userid=100;
Upvotes: 1
Reputation: 1732
You can read more about select statements, joins, etc. here: MySQL Reference - Select Syntax
SELECT *
FROM image
JOIN article ON article.id = image.articleid;
Upvotes: 2
Reputation: 589
You can do it like this
SELECT * FROM images WHERE articleid IN (SELECT id FROM article WHERE userid=100; );
Hope this will help you.
Upvotes: 0
Reputation: 40318
SELECT * FROM image WHERE articleid
in(SELECT articleid FROM article WHERE userid=100)
Upvotes: 1