Question

There's a table message and a table sender, and I want to retrieve all "message information" associated to a specific id, along with the sender name and email. I have this query:

SELECT
    a.id,
    a.subject,
    a.body,
    a.sender_id,
    (
        SELECT b.name
        FROM sender b
        WHERE b.id = a.sender_id
        LIMIT 1
    ) AS sender_name,
    (
        SELECT b.email
        FROM sender b
        WHERE b.id = a.sender_id
        LIMIT 1
    ) AS sender_email,
    a.sent_time
FROM message a
WHERE a.id = <id>
LIMIT 1;

It works, but it has to perform two different SELECT subqueries to the same table. In this case (which is an extremely simplified example) it probably doesn't hurt the performance at all, but in a real-life scenario where a lot of fields have to be retrieved from an external table, the best way to do it is using a JOIN statement? Isn't it possible to have a SELECT subquery that retrieves many fields?

I'm using MySQL with MyISAM storage engine in case it matters.

Was it helpful?

Solution

Just join to the sender tables once in the FROM clause.

SELECT  a.id,
        a.subject,
        a.body,
        a.sender_id,
        b.name,
        b.email,
        a.sent_time
FROM    message a
INNER JOIN
        sender b
ON      b.id = a.sender_id       
WHERE a.id = <id>
LIMIT 1;

OTHER TIPS

Try this:

SELECT
    a.id,
    a.subject,
    a.body,
    a.sender_id,
    b.name AS sender_name,
    b.email AS sender_email,
    a.sent_time
FROM message a, sender b
WHERE a.id = <id>
AND b.id = a.sender_id
LIMIT 1;

If you really don't want to use a join, you could use concat in your subquery CONCAT(b.name,";",b.email) and later explode the result on ; - but I'd go for join :D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top