在这里,我尝试内部加入SEARCHED_TAGS表和USER表。在这里,我使用三次相同的连接。不仅如此,我多次使用此查询。这会导致查询速度变慢吗?我怎么能一次写这个查询而不是3次。
您可以在下面看到查询。
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
inner join USER usr
on st.SEARCH_BY=usr.USER_ID
where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
UNION
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
inner join USER usr
on st.SEARCH_BY = usr.USER_ID
where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
UNION
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
inner join USER usr
on st.SEARCH_BY= usr.USER_ID
where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
我可以这样写而不是上面。
inner join USER usr
on st.SEARCH_BY=usr.USER_ID
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
UNION
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
UNION
(
select st.SEARCH_TEXT as SEARCH_TEXT
from SEARCHED_TAGS st
where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
order by st.SEARCH_TIME desc
limit 2
)
谢谢..
答案 0 :(得分:1)
由于限制语句,这可能是普通MySQL可以做到的最好的。但是使用会话变量我们可以做得更好:
SELECT SEARCH_TEXT
FROM
(
SELECT SEARCH_TEXT, grp,
(@num:=if(@group = grp, @num +1, if(@group := grp, 1, 1))) row_number
FROM
(
SELECT
st.SEARCH_TEXT as SEARCH_TEXT,
st.SEARCH_TIME,
CASE WHEN (st.SEARCH_TEXT like :tagText) AND (st.SEARCH_BY = :userId) AND
(usr.DEP_ID = :userDep) THEN 1
WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND
(usr.DEP_ID = :userDep) THEN 2
WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND NOT
(usr.DEP_ID = :userDep) THEN 3
ELSE 4 END AS grp
FROM SEARCHED_TAGS st
INNER JOIN USER usr
ON st.SEARCH_BY = usr.USER_ID
) t1
CROSS JOIN (select @num:=0, @group:=null) t2
ORDER BY grp, t1.SEARCH_TIME DESC
) t
WHERE
t.row_number <= 2 AND
t.grp <= 3;
此代码未经测试,主要是因为您的查询过于复杂而无法轻松进行测试,但如果遇到任何问题,我可以与您进行迭代。