我有一个网站供用户查看,让我们说“水果”和“蔬菜”。 我有一个fruit_review和一个vegetable_review表。两者都有reviewId,fruitName / vegetableName,reviewText和date字段。
我想在我的索引页面上做一个“最后5条评论”部分。例如。
为此,我使用以下查询:
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;
这很有效,但我想将这些结果用作评论的链接。
如何确定我刚收到的评论是属于水果还是蔬菜?(href =“vegetablereview.php?id = $ id”或href =“fruitreview.php?id = $ id“为每个案例?”
我可以在查询中包含一些内容,例如,我可以在php中处理表格的名称吗?
我不想在表中添加任何额外的列(例如,类型列对于水果总是0,对于蔬菜总是1)。
答案 0 :(得分:1)
您也可以使用union all
。效率更高:
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;
换句话说,你必须明确地处理它。除非您明确指定,否则MySQL无法识别特定列的表。
答案 1 :(得分:0)
您可以添加自定义字段(类型)并使用每行的文本水果或蔬菜填充它。
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;