我尝试从两个不同的不相关表中选择结果showcase
和questions
以显示在Feed中。它们应该由公共列hotness
排序,这是一个浮点值。
SELECT s.id,s.date,s.title,s.views,s.image,s.hidpi,s.width,s.description,u.display_name,u.avatar
FROM showcase AS s
INNER JOIN users AS u ON s.user_id = u.id
UNION
SELECT q.id,q.date,q.title,q.views,q.text,u.display_name,u.avatar,0,0,0
FROM questions AS q
INNER JOIN users AS u ON q.user_id = u.id
ORDER BY hotness DESC
LIMIT 10
我已尝试UNION
,但我不知道我应该如何在此处使用它并收到此错误unknown column hotness
答案 0 :(得分:0)
您可以尝试此查询:
SELECT r.* FROM (
SELECT s.id,s.date,s.title,s.views,s.image,s.hidpi,s.width,s.description,u.display_name,u.avatar, s.hotness
FROM showcase AS s
INNER JOIN users AS u ON s.user_id = u.id
UNION
SELECT q.id,q.date,q.title,q.views,q.text,u.display_name,u.avatar,0,0,0, q.hotness
FROM questions AS q
INNER JOIN users AS u ON q.user_id = u.id
) as r
ORDER BY r.hotness DESC
LIMIT 10
您需要在子查询中合并Union结果以在结果上应用Order by。我也在select子句中添加了hotness,请检查我从好的表中选择字段。
答案 1 :(得分:0)
您需要选择值才能让ORDER BY
识别它:
SELECT s.id,s.date,s.title,s.views,s.image,s.hidpi,s.width,s.description,u.display_name,u.avatar, s.hotness
FROM showcase AS s
INNER JOIN users AS u ON s.user_id = u.id
UNION ALL
SELECT q.id,q.date,q.title,q.views,q.text,u.display_name,u.avatar,0,0,0, q.hotness
FROM questions AS q
INNER JOIN users AS u ON q.user_id = u.id
ORDER BY hotness DESC;
请注意,我还将UNION
更改为UNION ALL
。除非您打算删除重复项,否则没有理由进行额外的处理。