我有一个用户表,其中包含用户的完整名称。链接表是:
用户
user_picture
user_visit
user_question
活动报告必须显示以下活动:
...但仅限我之前访问过的用户或之前收到过我的问题的用户。
这是我目前的查询:
SELECT SQL_CALC_FOUND_ROWS
user.name,
user_question.date_question,
user_question.question,
user_question.answer,
user_picture.date_picture,
user_picture.description
FROM
user
LEFT JOIN user_question ON user_question.id_user_to = user.id_user
LEFT JOIN user_picture ON user_picture.id_user = user.id_user
WHERE (
user.id_user IN (
SELECT id_user FROM user
INNER JOIN user_visit ON user_visit.id_user_to = user.id_user
INNER JOIN user_question ON user_question.id_user_to = user.id_user
WHERE
user_visit.id_user_from = 1
OR
user_question.id_user_from = 1
)
)
在此示例中,ID 1是我的用户ID。目前的问题:
关于如何解决这两个问题的任何想法?谢谢!
答案 0 :(得分:1)
看起来你正在尝试做两个查询,然后按日期顺序散布他们的结果......你可能需要UNION。 然后使用子选择来对结果进行排序。
SELECT SQL_CALC_FOUND_ROWS, *
FROM (
SELECT
user.name,
'picture' as type,
user_visit.date_visit as date,
user_picture.date_picture as data1,
user_picture.description as data2
FROM
user
JOIN user_visit ON (user_visit.id_user_to = user.id_user)
JOIN user_picture ON (user_picture.id_user_to = user.id_user)
WHERE user_visit.id_user_from = 1
UNION
SELECT
user.name,
'question' as type,
user_question.date_question as date,
user_question.question as data1,
user_question.answer as data2,
FROM
user
JOIN user_question ON user_question.id_user_to = user.id_user
WHERE user_question.id_user_from = 1
)
ORDER BY date;
答案 1 :(得分:0)
要解决第一个问题,我认为您还需要加入user_visit表,并按日期顺序加入ORDER BY。
SELECT SQL_CALC_FOUND_ROWS
user.name,
user_question.date_question,
user_question.question,
user_question.answer,
user_picture.date_picture,
user_picture.description,
user_visit.date_visit
FROM
user
LEFT JOIN user_question ON user_question.id_user_to = user.id_user
LEFT JOIN user_picture ON user_picture.id_user = user.id_user
LEFT JOIN user_visit ON user_visit.id_user_from = user.id_user
WHERE (
user.id_user IN (
SELECT id_user FROM user
INNER JOIN user_visit ON user_visit.id_user_to = user.id_user
INNER JOIN user_question ON user_question.id_user_to = user.id_user
WHERE
user_visit.id_user_from = 1
OR
user_question.id_user_from = 1
)
)
ORDER BY user_visit.date_visit, user_question.date_question
这有可能吗?你能详细说明你的第二个问题吗?也许举个例子?