简体   繁体   English

MySQL在常见查询中分开两个表

[英]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. 我有一个fruit_review和一个vegetable_review表。 Both have reviewId, fruitName/vegetableName, reviewText and date fields. 两者都有reviewId,fruitName / vegetableName,reviewText和日期字段。

I would like to make a "last 5 reviews" section on my index page for example. 例如,我想在索引页面上进行“最后5条评论”部分。

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?) (对于每种情况,href =“ vegetablereview.php?id = $ id”还是href =“ fruitreview.php?id = $ id”?)

Can I include something to the query, which gives back for example the table's name what I can handle in php? 我可以在查询中包含一些内容吗,例如,该表可以返回我可以在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). 我不想在表中添加任何额外的列(例如,对于水果,对于蔬菜始终为0的类型列)。

You might as well use union all . 您不妨使用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. 除非明确指定,否则MySQL无法识别特定列的表。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM