I was listing this two queriess as separate, but now I need the results in the same list.
Right now I have it ‘fixed’ by ordering the items by id using javascript. But it would be great to get this data merged from the server so I would be able to page the results..
DATABASE SCHEMA
Table Friends:

Table helps

Query A (returns results from the current user)
$sql = 'SELECT * FROM helps WHERE id_user ='.$value;
Query B (returns results from the current user’s friends)
$sql = 'SELECT
h.*,
f.*
FROM (
SELECT
id AS friendsId,
CASE followerid WHEN '.$value.' THEN followingid ELSE followerid END AS friend_id
FROM friends
WHERE acepted = 1
AND (followerid = '.$value.' OR followingid = '.$value.')
) AS f
INNER JOIN helps AS h ON h.id_user = f.friend_id
ORDER BY h.id DESC';
Is there a way to merge these queries? I honestly have no clue how to.
-EDIT-
Considering union, but I don’t know how to handle the order by thing..
$sql = '(SELECT * FROM helps WHERE id_user = '.$value.')
UNION
(SELECT
h.*,
f.*
FROM (
SELECT
id AS friendsId,
CASE followerid WHEN '.$value.' THEN followingid ELSE followerid END AS friend_id
FROM friends
WHERE acepted = 1
AND (followerid = '.$value.' OR followingid = '.$value.')
) AS f
INNER JOIN helps AS h ON h.id_user = f.friend_id
ORDER BY h.id DESC)';
As you can see in the second query helps table has been renamed to h. How can I do the same in the first? (both queries return the data in the same format)
The basic rules of
UNIONareAs you can see, i haven’t modified the queries you formulated. Only that I added a Virtual Column for each query. This column will be used for ordering all the records. The queries were wrap by another
select statmentso the virtual column won’t show on the result list but it will be the basis for ordering the records. The result of the query below contains the records of the user at the top most (because ofORDER BY OrderBy ASC) and the followed by the records of the user’s friends sorted by friend’s ID. If any clarification you want, please do inform me. One more thing, I removedf.*in your second query because it is not necessary and can cause error on your syntax due to column (number) mismatched.