user3897338
user3897338

Reputation:

MySQL separate two tables in common query

I have a website where users can review let's say 'fruits' and 'vegetables'. I have a fruit_review and a vegetable_review table. Both have reviewId, fruitName/vegetableName, reviewText and date fields.

I would like to make a "last 5 reviews" section on my index page for example.

To do this, I use the following query:

SELECT reviewId AS id, fruitName AS name, reviewText AS text, date FROM fruit_review
UNION
SELECT reviewId AS id, vegetableName AS name, reviewText AS text, date FROM vegetable_review
ORDER BY date DESC LIMIT 5;

This works well, but I would like to use these results as a link to the review.

How can I decide if the reviews I just got are belong to fruits or vegetables?(href="vegetablereview.php?id=$id" or href="fruitreview.php?id=$id" for each case?)

Can I include something to the query, which gives back for example the table's name what I can handle in php?

I would not like to add any extra columns to the tables (for example a type column which is always 0 for fruits and 1 for vegetables).

Upvotes: 0

Views: 251

Answers (2)

phicon
phicon

Reputation: 3617

You could add a custom field (type) and fill it with the Text Fruit or Vegetable for each line.

SELECT reviewId AS id, fruitName AS name, 'fruit' as type, reviewText AS text, date FROM fruit_review
UNION
SELECT reviewId AS id, vegetableName AS name, 'vegetable' as type, reviewText AS text, date FROM vegetable_review
ORDER BY date DESC LIMIT 5;

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269973

You might as well use union all. It is more efficient:

SELECT 'fruit' as which, reviewId AS id, fruitName AS name, reviewText AS text, date FROM fruit_review
UNION ALL
SELECT 'vegetable' as which, reviewId AS id, vegetableName AS name, reviewText AS text, date FROM vegetable_review
ORDER BY date DESC
LIMIT 5;

In other words, you have to handle it explicitly. MySQL doesn't have the ability to identify the table for a particular column, unless you specify it explicitly.

Upvotes: 1

Related Questions