我有两张桌子。第一个表看起来像这样:
表:记录
rid | user id | title | whenadded | public -------------------------------------------------------------------- 1 212 Example 2012-06-28 1 2 217 Test Rec 2012-07-05 1 3 212 Another 2012-07-02 1 4 212 Unlisted 2012-05-02 0 5 217 Success 2012-04-08 1 6 238 Always 2012-04-18 1
表:喜欢
id | user id | rid | whenliked ------------------------------------------------------ 1 212 2 2012-07-06 2 205 1 2012-06-30 3 212 5 2012-07-04
在'唱片'表,' rid'被设置为主索引。在'喜欢' table,id被设置为主索引。
我正在使用PHP。 PHP将为MySQL提供一个值作为参考。我想要一个MySQL查询,它将执行以下操作:
伪代码:
$userid = 212;
$SQL = 'SELECT DISTINCT records.*
FROM records,likes
WHERE (records.userid = ' . $userid .
' AND records.public = 1)
OR (records.id = likes.rid AND likes.userid = ' . $userid .
' AND records.public = 1)
ORDER BY likes.whenliked DESC, records.whenadded DESC
LIMIT 50;';
查看我刚才提供的$ SQL查询。这是我尝试开发我想要的查询,但它没有达到我想要的效果;它非常接近,但仍然订购不正确。该查询是我自己开发的最好的,然后根据我在StackFlow和Google上的其他地方搜索解决方案找到的。
这些是我试图通过以下方式订购的条件:
返回的查询的最终结果看起来像这样(请记住,当回复数据不在时,它只是在那里供参考,所以你看看它是如何订购的):
rid | user id | title | whenadded | public | whenliked {not incl} ------------------------------------------------------------------------------------ 2 217 Test Rec 2012-07-05 1 2012-07-06 3 212 Another 2012-07-02 1 5 217 Success 2012-04-08 1 2012-06-30 1 212 Example 2012-06-28 1
希望这是有道理的。随意提问,我会尽我所能澄清。
提前感谢您的时间,您的考虑以及阅读本文。即使没有响应或找不到解决方案,您的时间仍然非常感谢! :)
答案 0 :(得分:4)
您订购的字段不必是数据库中的现有字段。您还可以使用您在选择中定义的字段:
SELECT IF(records.userid = ' . $userid . ', records.whenadded, likes.whenliked) as date
现在您可以按部分顺序使用它:
ORDER BY date DESC
来自MySQL Manual:
可以使用AS alias_name为select_expr指定别名。别名用作表达式的列名,可用于GROUP BY,ORDER BY或HAVING子句
答案 1 :(得分:1)
我建议将查询分成2个查询并改为使用UNION。
SELECT * FROM(
(SELECT records.rid, records.userid,records.title, records.whenadded as adate
FROM records,likes
WHERE records.userid = $userid AND records.public = 1 )
UNION
(SELECT records.rid, records.userid,records.title, likes.whenliked as adate
FROM records,likes
WHERE records.rid = likes.rid AND likes.userid = $userid
AND records.public = 1)
)t ORDER BY adate DESC
EDITED: 请参阅http://sqlfiddle.com/#!2/9a877/4
答案 2 :(得分:0)
这个怎么样:
$userid = 212;
$SQL = 'SELECT DISTINCT records.*
FROM records,likes
WHERE (records.userid = ' . $userid .
' AND records.public = 1)
OR (records.id = likes.rid AND likes.userid = ' . $userid .
' AND records.public = 1)
ORDER BY records.userid, likes.whenliked DESC, records.whenadded DESC
LIMIT 50;';
这将首先按用户分类,逐个用户分开,然后按日期分开。
答案 3 :(得分:0)
根据我的评论,这是您应该查看的另一个查询:
SELECT
records.*
FROM records
LEFT JOIN likes ON records.rid = likes.rid
WHERE records.public = 1
AND COALESCE(likes.userid, records.userid) = $userid
ORDER BY COALESCE(likes.whenliked, records.whenadded) DESC;
它假设你不能不止一次记录并且能够驾驭奇怪的DISTINCT。
COALESCE is here的文档。
此查询不是真正的性能。如果你有一个非常大的数据库,将查询拆分为两个,以便以全功率用户身份上的索引,然后再次加入它们可能会更好。